2015-03-02 62 views
0

我有這個集合...如何用這個命令得到這個查詢MongoDB中

> db.banks.find().pretty() 
{ 
     "_id" : ObjectId("54f37cbb44aec3b01b7db8f4"), 
     "name" : "A", 
     "branches" : [ 
       { 
         "branch_id" : 8561, 
         "name" : "X",        
       }, 
       { 
         "branch_id" : 8576, 
         "name" : "Y",        
       } 
     ] 
} 
{ 
     "_id" : ObjectId("54f37cbb44aec3b01b7db8f5"), 
     "name" : "B", 
     "branches" : [ 
       { 
         "branch_id" : 3238, 
         "name" : "Z",        
       } 
     ] 
} 

db.banks.aggregate({$project{"branches.name":1,"_id":0}}); 

得到這樣的結果:

{ "branches" : { { "name" : "X" }, { "name" : "Y" } } } 
{ "branches" : { { "name" : "Z" } } } 

但是,我如何得到這個結果? (事實上,一個對象,並沒有「樹枝」。)

{{"name" : "X"}, {"name" : "Y"}, {"name" : "Z"}} 

非常感謝...

回答

1

一個你可以去這個問題的方法是做一個$unwind首先在聚合管道獲得解構陣列與由陣列元件$branches.name爲每個元素的文檔,然後組:

db.banks.aggregate([ 
    { $unwind: '$branches'}, 
    { 
     $group: { 
      _id: { 
       name: '$branches.name' 
      } 
     } 
    }, 
    { 
     $project: { 
      _id: 0, 
      name: '$_id.name' 
     } 
    }, 
    { $sort : { "name" : 1 } } 
]) 

輸出:

{ 
    "result" : [ 
     { 
      "name" : "X" 
     }, 
     { 
      "name" : "Y" 
     }, 
     { 
      "name" : "Z" 
     } 
    ], 
    "ok" : 1 
}