2014-01-29 22 views
0

我的文件看起來像檢索子文檔:MongodDB屬性名

{ "entity_id" : 2, 
    "features" : 
    [ 
    { "10" : "name" }, 
    { "20" : "description" }, 
    ... , 
    { "90" : "availability" } 
    ] 
} 

我想,知道兩件事情:「ENTITY_ID」(2)的值,屬性的一個值的「特徵」數組的元素,來檢索子文檔

{ "20" : "description" } 

在一個查詢。非常感謝!

+0

.find({'features.20':{$ exists:true}}) – portforwardpodcast

+0

這將給出整個文檔。我只想要屬性是20的元素文件 – Alex

+0

http://stackoverflow.com/questions/9289384/select-only-subdocuments-or-arrays – portforwardpodcast

回答

0

如果你想只得到了整個文檔的一部分,使用所謂的Projection operators

請參見下面的例子:

> db.collection.find().pretty() 
{ 
    "_id" : ObjectId("52e861617acb7ce761e64a93"), 
    "entity_id" : 2, 
    "features" : [ 
     { 
      "10" : "name" 
     }, 
     { 
      "20" : "description" 
     }, 
     { 
      "90" : "availability" 
     } 
    ] 
} 

投影運營商都在尋找(指定)喜歡這裏:

> db.collection.find({},{ features : { $elemMatch : { 20 : { $exists: true } }}}).pretty() 
{ 
    "_id" : ObjectId("52e861617acb7ce761e64a93"), 
    "features" : [ 
     { 
      "20" : "description" 
     } 
    ] 
} 

> db.collection.find({},{ entity_id : 1, features : { $elemMatch : { 20 : { $exists: true } }}}).pretty() 
{ 
    "_id" : ObjectId("52e861617acb7ce761e64a93"), 
    "entity_id" : 2, 
    "features" : [ 
     { 
      "20" : "description" 
     } 
    ] 
} 
> db.collection.find({},{ _id : 0, entity_id : 1, features : { $elemMatch : { 20 : { $exists: true } }}}).pretty() 
{ "entity_id" : 2, "features" : [ { "20" : "description" } ] } 

$elemMatch for projection在自2.2版以來的MongoDB中可用。

希望它能解決您的問題。

+0

這些都沒有回報我在找什麼。我錯過了什麼嗎?你測試過它們嗎? – Alex

+2

也許你應該考慮在你的問題中包含你期望的輸出,如果這不是你的意思,因爲似乎有混淆?我將MongoDB控制檯的輸出與查詢一起粘貼到了你的面前,因此,「我是否測試了這些查詢」這個問題有點荒謬。 –

+0

從我的問題: 在一個查詢中檢索文檔{「20」:「description」} – Alex