2012-12-31 139 views
3

這裏是例子MongoDB的子元素查詢

> db.test.insert({ name: 'test', values: [ { check: true }, { check: false } ] }) 
> db.find({ values.check: true })[0] 

,所以我得到真假兩check

{ 
     "_id" : ObjectId("50e22046dc278908f3a38a8e"), 
     "name" : "test", 
     "values" : [ 
       { 
         "check" : true 
       }, 
       { 
         "check" : false 
       } 
     ] 
} 

,我想這一點:

{ 
     "_id" : ObjectId("50e22046dc278908f3a38a8e"), 
     "name" : "test", 
     "values" : [ 
       { 
         "check" : true 
       } 
     ] 
} 

有什麼爲此過濾命令?

回答

0
> db.test.aggregate(
{ $unwind: "$values" }, 
{ $match: { "values.check": true } } 
).result 

[ 
     { 
       "_id" : ObjectId("50e22046dc278908f3a38a8e"), 
       "name" : "test", 
       "values" : { 
         "check" : true 
       } 
     } 
] 
0
$fetchcode = "Fetch an array from the mongo db" 
    foreach ($fetchcode as $mainkey => $mainVariable) { 
     foreach($mainVariable as $key2 => $doc2) 
     { 
      if($key2 == "check"){ 
       if($doc2 == "true") 
       { 
        //Your Function Here 
       } 
      } 
     } 
    } 

你可以試試這個

+0

我需要mongodb解決方案而不是php –

3

可以使用$投影算到包括匹配查詢只是第values數組元素:

db.test.find({ 'values.check': true }, {name: 1, 'values.$': 1}) 

回報:

{ 
    "_id": ObjectId("50e22046dc278908f3a38a8e"), 
    "name": "test", 
    "values": [ { "check": true } ] } 
+0

感謝您的答案。是否有機會匹配不僅僅是一個,而是所有真實的值? –

+0

我剛剛聽說$ elemMatch我認爲這是答案 –

+0

$ eleMatch也只返回匹配的第一個元素。請參閱[本文](http://stackoverflow.com/questions/3985214/mongodb-extract-only-the-selected-item-in-array/12241930)以瞭解如何使用聚合框架來包含所有匹配元素的詳細信息。 – JohnnyHK