2017-04-18 87 views
0

我有大集合的文檔MongoDB具有以下結構爲例:複雜的MongoDB集合查詢

{ "key" : "a" ,"data" : "value1" , "lastname" : "Doe" }<br> 
{ "key" : "ab" , "data" : "value1" , "lastname" : "Doe" }<br> 
{ "key" : "abc" , "data" : "value1" , "lastname" : "Doe" } <<< <br> 
{ "key" : "d" ,  "data" : "value2" , "lastname" : "Doe" }<br> 
{ "key" : "df" , "data" : "value2" , "lastname" : "Doe" }<br> 
{ "key" : "dfg" , "data" : "value2" , "lastname" : "Doe" } <<< <br> 

我需要根據條件由<<<標記這兩行得到的數據key上這些線路 已經包括從其他文件一樣lastname即「ABC」有「AB」和「AB」有「一個」鍵值,導致我需要應該是這樣的:

{ "lastname" : "Doe" , "value1" : "abc" , "value2" : "dfg" } 

我可以通過創建2個單獨的查詢來獲取數據,但是我想查看是否可以在一箇中完成。

+0

的可能的複製[?我如何執行SQL加入MongoDB中相當於(http://stackoverflow.com/questions/2350495/how-do-i-執行最SQL聯接等效功能於MongoDB中) – str

回答

0

尚未完全格式化:

db.coll.aggregate([ 
{$project: {key:1, root: '$$ROOT', lastname: 1, data: 1, keyLength: {$strLenBytes: '$key'}, keyIndexes: {$range:[0, {$strLenBytes: '$key'}]}}}, 
{$unwind: '$keyIndexes'}, 
{$group: {items: {$push: '$root'}, count: {$sum: 1}, _id: {$substrBytes: ['$key', '$keyIndexes', 1]}}}, 
{$match: {count: 1}}, 
{$group: {_id: '$items.lastname', items: {$push: {$arrayElemAt: ['$items', 0]}}}} 
]).pretty() 
{ 
    "_id" : [ 
     "Doe" 
    ], 
    "items" : [ 
     { 
      "_id" : ObjectId("58f62e5433530ab32f554fd6"), 
      "key" : "abc", 
      "data" : "value1", 
      "lastname" : "Doe" 
     }, 
     { 
      "_id" : ObjectId("58f62e5433530ab32f554fd9"), 
      "key" : "dfg", 
      "data" : "value2", 
      "lastname" : "Doe" 
     } 
    ] 
}