2017-03-07 41 views
1

我有一個關於MongoDB聚合查詢的問題,它幾乎類似於$unwind 2 fields separately in mongodb queryMongoDB分別展開2個嵌入式陣列

這是文件:

{ 
    "_id" : "1", 
    "details" : { 
     "phonenumber" : [ 
      "1", 
      "2" 
     ], 
     "name" : [ 
      "a", 
      "b" 
     ] 
    } 
} 

,我試圖來構建查詢將返回我以下結果:

{ "_id" : "1", "phonenumber" : "1", "name" : null }, 
{ "_id" : "1", "phonenumber" : "2", "name" : null }, 
{ "_id" : "1", "phonenumber" : null, "name" : "a" }, 
{ "_id" : "1", "phonenumber" : null, "name" : "b" } 

可能有人請幫助我嗎?

我能想出

最近的解決方案是通過以下查詢:

db.document.aggregate([ { $unwind: { path: "$details.name"} }, { $unwind: { path: "$details.phonenumber" } }, { $project: { _id: 1, name: "$details.name", phonenumber: "$details.phonenumber" } } ]) 

而且從上述查詢的輸出爲:

{ "_id" : "1", "phonenumber" : "1", "name" : "a" }, 
{ "_id" : "1", "phonenumber" : "1", "name" : "b" }, 
{ "_id" : "1", "phonenumber" : "2", "name" : "a" }, 
{ "_id" : "1", "phonenumber" : "2", "name" : "b" } 
+0

你可以給你的集合中的文檔的完整的例子嗎?在你的嘗試中,你有'$ details.email'。 –

+0

聚合流水線是順序的。一個階段的輸出將被輸入到另一個階段。你要做的是將初始數據分成兩個階段。這是不可能的。 – RaR

+0

@ʰᵈˑ我在問題中編輯了'email'字段和'name'。這是一個錯字。 –

回答

1

隨着MongoDB v3.4,可能的解決方案將是一個,

db.document.aggregate({ 
    '$facet': { 
     'phonenumber': [{ 
      '$unwind': '$details.phonenumber' 
     }, { 
      '$project': { 
       phonenumber: '$details.phonenumber', 
       name: null 
      } 
     }], 
     'name': [{ 
      '$unwind': '$details.name' 
     }, { 
      '$project': { 
       name: '$details.name', 
       phonenumber: null 
      } 
     }] 
    } 
}, { 
    '$project': { 
     'combined': { 
      '$setUnion': ['$phonenumber', '$name'] 
     } 
    } 
}, { 
    '$unwind': '$combined' 
}, { 
    '$replaceRoot': { 
     'newRoot': '$combined' 
    } 
}) 

facet允許我們公司一個階段,這是從版本爲早期版本的MongoDB 3.4

1

替代的解決方案中的路得多個聚合管道,

db.document.aggregate([{ 
     $unwind: { 
      path: "$details.name" 
     } 
    }, { 
     $group: { 
      _id: "$_id", 
      nameArr: { 
       $push: { 
        name: "$details.name", 
        phonenumber: { 
         $ifNull: ["$description", null] 
        } 
       } 
      }, 
      "details": { 
       $first: "$details" 
      } 
     } 
    }, { 
     $unwind: "$details.phonenumber" 
    }, { 
     $group: { 
      _id: "$_id", 
      phoneArr: { 
       $push: { 
        phonenumber: "$details.phonenumber", 
        name: { 
         $ifNull: ["$description", null] 
        } 
       } 
      }, 
      "nameArr": { 
       $first: "$nameArr" 
      } 
     } 
    }, { 
     $project: { 
      _id: 1, 
      value: { 
       $setUnion: ["$nameArr", "$phoneArr"] 
      } 
     } 
    }, { 
     $unwind: "$value" 
    }, { 
     $project: { 
      name: "$value.name", 
      phonenumber: "$value.phonenumber" 
     } 
    }]) 
+0

這也適用!謝謝 :) –