【问题标题】:Mongo 3.6 aggregation lookup with multiple conditions具有多个条件的 Mongo 3.6 聚合查找
【发布时间】:2018-01-30 18:44:55
【问题描述】:

假设我有一个只有一个集合 data 的 Mongo DB。在这个集合中,我有以下文档:

{
    "type": "person",
    "value": {
        "id": 1,
        "name": "Person 1",
        "age": 10
    }
},
{
    "type": "person",
    "value": {
        "id": 2,
        "name": "Person 2",
        "age": 20
    }
},
{
    "type": "prescription",
    "value": {
        "drug": "Bromhexine",
        "patient": 2
    }
},
{
    "type": "prescription",
    "value": {
        "drug": "Aspirin",
        "patient": 1
    }
}

有了这些记录,我想在 value.id = value.patient 上使用 "type": person"type": prescription 的文档之间进行 JOIN。

我已经尝试了以下阶段的聚合:

{
    "$match": {
        "type": "person"
    }
},
{
    "$lookup": {
        "from": "data",
        "let": { "patient": "$value.id"},
        "pipeline": [
            {
                "$match": {
                    "$expr": {
                        "type": "prescription",
                        "value.patient": "$$patient"
                    }
                }
            }
        ],
        "as": "prescription"
    }
}

但它会产生错误FieldPath field names may not contain '.'。我相信这是由于"let": { "patient": "$value.id"}, 行。相反,如果我尝试使用双美元符号 ($$)(如 here 所示),则结果是错误 Use of undefined variable: value

知道如何进行这种聚合吗?

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework lookup aggregation


    【解决方案1】:

    $lookup 阶段内完成以下管道对象

    "pipeline": [
                    { "$match":
                        { "$expr":
                            { "$and":
                                [
                                    { "$eq": [ "$type", "prescription" ] },
                                    { "$eq": [ "$value.patient",  "$$patient" ] }
                                ]
                            }
                        }
                    }
                ]
    

    【讨论】:

      猜你喜欢
      • 2014-12-12
      • 1970-01-01
      • 2019-07-16
      • 2020-10-02
      • 2018-08-18
      • 2020-08-26
      • 1970-01-01
      • 1970-01-01
      • 2022-11-29
      相关资源
      最近更新 更多