【问题标题】:MongoDB: Lookup - Collections with Same FieldsMongoDB:查找 - 具有相同字段的集合
【发布时间】:2019-02-26 15:08:26
【问题描述】:

我有两个集合 UsersNotes。两个集合都包含一个id 属性,而Notes 集合有一个userid,它是Users 集合中某个用户的ID。

现在,我正在尝试将一些用户信息聚合(加入)到Notes

db.getCollection("Notes").aggregate(
{
    "$lookup": {
        "from": "Users",
        "let": {
            "idForeignField": "$id"
        },
        "pipeline": [
                            {
            "$match": {
                "$expr": {
                    "$and": [{
                        "$eq": ["$userid", "$$idForeignField"]
                    }]
                }
            }
                            }
        ],
        "as": "Users#joined"
    }
}
);

我在一个空的 Users#joined 数组中得到了什么。为什么?我的查询不应该工作吗?问题是由两个集合都有id 属性引起的吗?如果是,我怎么知道letmatch 什么是正确的集合?

更新:或者更简单的查询也可以:

db.getCollection("Notes").aggregate(
{
   $lookup:
     {
       from: "Users",
       localField: "userid",
       foreignField: "id",
       as: "Users#joined"
     }
}
);

但是我想使用let 和管道来添加更多match 条件。

谢谢。

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework


    【解决方案1】:

    您的let 变量必须是userid

    db.getCollection("Notes").aggregate([
      { "$lookup": {
        "from": "Users",
        "let": { "ifForeignField": "$userid" },
        "pipeline": [
          { "$match": { "$expr": { "$and": [{ "$eq": ["$id", "$$ifForeignField"] }] }}}
        ],
        "as": "Users#joined"
      }}
    ])
    

    【讨论】:

      猜你喜欢
      • 2023-03-15
      • 1970-01-01
      • 2016-07-29
      • 2017-08-12
      • 2022-12-05
      • 1970-01-01
      • 1970-01-01
      • 2015-07-14
      • 2021-11-30
      相关资源
      最近更新 更多