MongoDB: 如何在不反规范化的情况下通过键从另一个集合中获取所有文档?

MongoDB: How to get all documents by the keys from another collections without de-normalization?

假设我们有两个集合:一个 topics 和一个 posts。我们有一个 user._id:

topic  {
    _id, // topicID
    userId
}

post {
    topicId
}

user {
    _id
}

如何在 MongoDB 中通过特定的 user 获取所有 posts而不在 post[=25 中存储 userId =])?

(post.topicId === topic._id) && (topic.userId === user._id)

您可以在主题数组上使用 $lookup operator to do a left join on the unsharded topic collection, then filter the resulting documents using a $match pipeline. You may need to use the $filter 运算符以仅包含与给定用户 ID 条件匹配的子文档。下面演示了这种方法:

db.post.aggregate([
    {
        "$lookup": {
            "from": "topic",
            "localField": "topicId",
            "foreignField": "_id",
            "as": "topics"
        }
    },
    { "$match": { "topics.userId": user._id } },
    {
        "$project": {
            "topics": {
                "$filter": {
                    "input": "$topics",
                    "as": "item",
                    "cond": { "$eq": [ "$$item.userId", user._id ] }
                }
            }
        }
    }
])