2015-02-07 192 views
0

我正在下面的文件文檔中查找子元素MongoDB中

{ 
"_id" : 123344223, 
"firstName" : "gopal", 
"gopal" : [ 
    { 
     "uuid" : "123", 
     "name" : "sugun", 
     "sudeep" : [ 
      { 
       "uuid" : "add32", 
       "name" : "ssss" 
      }, 
      { 
       "uuid" : "fdg456", 
       "name" : "gfg" 
      } 
     ] 
    }, 
    { 
     "uuid" : "222", 
     "name" : "kiran" 
    } 
] 
} 

我想我的輸出如下

{ 
"_id" : 456, 
"gopal" : [ 
    { 
     "uuid" : "123", 
     "name" : "sugun", 
     "sudeep" : [ 
      { 
       "uuid" : "add32", 
       "name" : "ssss" 
      } 
     ] 
    } 
] 
} 

,我試圖像

db.People.findOne({_id:123},{gopal:{$elemMatch:{uuid:"123",sudeep:{$elemMatch:{uuid:"add32"}}}}}); 
很多東西

但無論我嘗試它返回這樣的文件

{ 
"_id" : 123, 
"gopal" : [ 
    { 
     "uuid" : "123", 
     "name" : "sugun", 
     "sudeep" : [ 
      { 
       "uuid" : "add32", 
       "name" : "ssss" 
      }, 
      { 
       "uuid" : "fdg456", 
       "name" : "gfg" 
      } 
     ] 
    } 
] 
} 

你能幫忙嗎?

+0

[只檢索對象數組中的查詢元素在MongoDB集合](http://stackoverflow.com/questions/3985214/retrieve-only-the-queried-element-in-an-object-array-in-mo ngodb收集) – styvane 2016-01-08 08:16:39

回答

2

您是否知道MongoDB aggregation pipeline?在聚合管道

> db.people.aggregate([ 
    {$match: {_id: 123}}, 
    {$unwind: "$gopal"}, 
    {$unwind: "$gopal.sudeep"}, 
    {$match: {"gopal.uuid": "123", "gopal.sudeep.uuid" : "add32"}} 
]) 

輸出

{ 
     "_id" : 123, 
     "firstName" : "gopal", 
     "gopal" : { 
       "uuid" : "123", 
       "name" : "sugun", 
       "sudeep" : { 
         "uuid" : "add32", 
         "name" : "ssss" 
       } 
     } 
} 
0

使用$開卷

db.People.aggregate([{$比賽:{_ ID: '123'}},{$匹配:{ gopal.uuid:'123'}},{$ unwind:'$ sudeep'},{$ match:{uuid:'add32'}}])