如何将查找查询结果限制在 MongoDB 中两个字段匹配的位置?

How to restrict lookup query results to where two fields match in MongoDB?

赞table

{
    likedId: 'xxx'
    userId: '123'
}
{
    likedId: 'aaa'
    userId: '123'
}

帖子table

{
    postId: 'xxx'
    ...
}

评论table

{
    commentId: 'aaa'
    ...
}

Likestable记录'likes',可以是Posts也可以是Comments,分别存储在Posts和Comments集合中。我想做一个查找,仅 returns 其中 Likes table only 中的 id 匹配 Posts table 中的 id,并排除返回与帖子 table 不匹配的任何记录,例如示例中的 'aaa' id 对应于评论 table

中的条目

我能想到的唯一方法是按如下方式使用 'match',但我得到的是一个空数组。问题是,当我 运行 查询时,我得到空记录,其中 Likes table 中的 'likedId' 与 Posts table[= 中的任何文档都不匹配15=]

const pipeline = [
                {
                    '$lookup': {
                        'from': 'posts',
                        'localField': 'likedThing',
                        'foreignField': '_id',
                        'as': 'postData'
                    }
                }, {
                    '$match': {
                        'likedThing': 'postData._id'
                    }
                }, {
                    '$sort': {
                        'createdAt': -1
                    }
                }
            ]

我试图告诉它只给我 likedId 与 Posts 集合中的 _id 匹配的记录。请问这样可以吗?

你的问题来自你的匹配阶段,如果你想过滤没有任何帖子喜欢的记录(喜欢),你可以例如检查数组是否为空:

db.likes.aggregate([
  {
    "$lookup": {
      "from": "posts",
      "localField": "likedId",
      "foreignField": "postId",
      "as": "postData"
    }
  },
  {
    "$match": {
      "postData": {
        "$ne": []
      }
    }
  },
])

工作示例:https://mongoplayground.net/p/WSfe7gBkXkG

如果你想通过数组中的字段进一步匹配你可以使用$elemMatchhttps://docs.mongodb.com/manual/reference/operator/query/elemMatch/