如何对数组mongodb聚合执行多个$ lookup

时间:2018-11-26 19:39:51

标签: node.js mongodb mongoose aggregation-framework

如何为阵列总计(mongodb)执行$lookup

{
     messages: [{
            "_id" : ObjectId("5bfc43f2bbc4176ecc1c5f83"),
            "text" : "text1",
            "sender" : {
                    "id" : "36046fc2e70dd508a0bf1f36fd2daa20"
            }
         }, {
            "_id" : ObjectId("5bfc43f2bbc4176ecc1c5f83"),
            "text" : "text2",
            "sender" : {
                    "id" : "36046fc2e70dd508a0bf1f36fd2daa22"
            }
    }],
    "filed1": { ... },
    "filed2": { ... }
}

我如何为帐户收集中的发件人ID做$lookup

尝试:

...
      {
        $lookup: {
          from: "accounts",
          localField: "messages.sender.id",
          foreignField: "id",
          as: "messages.sender.user"
        }
      }
...

1 个答案:

答案 0 :(得分:1)

您可以使用以下汇总

db.collection.aggregate([
  { "$unwind": "$messages" },
  { "$lookup": {
    "from": "accounts",
    "localField": "messages.sender.id",
    "foreignField": "id",
    "as": "messages.sender.user"
  }},
  { "$unwind": "$messages.sender.user" }
  { "$group": {
    "_id": "$_id",
    "messages": { "$push": "$messages" },
    "filed1": { "$first": "$filed1" },
    "filed2": { "$first": "$filed2" }
  }}
])