且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

$ lookup聚合中的$ project

更新时间:2022-06-08 22:10:55

主要挑战是您要主文档中的所有字段(因为您不了解所有字段)加上2个从列表中.

The main challenge is that you want all fields from the main document (since you do not know all of them) plus only 2 from the list.

这应该做到:

{
  $project: {
    "_id": 0,
    "document": "$$CURRENT",
    "list._id": "$$CURRENT.list._id",
    "list.name": "$$CURRENT.list.name"
  }
}, {
  $project: {
    "document.list": 0
  }
}, {
  $addFields: {
    "document.list._id": "$$CURRENT.list._id",
    "document.list.name": "$$CURRENT.list.name"
  }
}, {
  $replaceRoot: {
    newRoot: "$document"
  }
}

它经历了几个阶段,但完成了工作:).它将使用当前文档以及仅所需的列表字段.然后它将从当前文档中删除其列表.然后,它将添加到同一文档列表(因为其中包含我们想要的特定字段).然后它将这些字段添加到文档中,最后将根替换为该文档.

It goes through few stages but gets the job done :). It would take the current document and only the list fields you want. Then it would remove from the current doc its list. Then it would add to that same doc the list (since that one is with the specific fields we want). Then it would add those fields to the document and lastly it would replace the root with that document.

在这里看到它正常运行.