如何查找嵌套的 属性?

How to lookup for nested property?

假设我有 2 个 collections

// Post collection:
{
    "_id": "post1",
    "title": "Some title"
}

// User collection:

{
    "_id": "user1",
    "posts": {
        "voted": [
            {
                 "_id": "post1",
                 "vote": 3
            },
            {
                 "_id": "post2",
                 "vote": 2
            }
        ]
    }
}

我需要得到这个结果:

{
    "_id": "post1",
    "title": "Some title",
    "voted": 3
}

我如何使用 聚合 发出请求,这将显示此输出?

这是我尝试过的:https://mongoplayground.net/p/oeKpVHo0uRe

简单选项:

 db.post.aggregate([
 {
   $match: {
  _id: "post1"
 }
 },
 {
  $lookup: {
  from: "user",
  localField: "_id",
  foreignField: "posts.voted._id",
  as: "Results"
 }
 },
 {
  $unwind: "$Results"
 },
 {
  $unwind: "$Results.posts.voted"
 },
 {
  $match: {
   "Results.posts.voted._id": "post1"
 }
 },
 {
  $project: {
   "voted": "$Results.posts.voted.vote",
   title: 1
 }
 }
 ])

解释:

  1. $仅匹配 post1 的帖子
  2. $join(lookup) 与用户集合
  3. $展开数组。
  4. $只匹配投给 post1 的人
  5. $project 需要的字段。

playground