具有多个条件的Mongo 3.6聚合查找 [英] Mongo 3.6 aggregation lookup with multiple conditions

查看:248
本文介绍了具有多个条件的Mongo 3.6聚合查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个只有一个集合data的Mongo数据库.在此收藏中,我有以下文档:

Suppose I have a Mongo DB with only one collection data. In this collection, I have the following documents:

{
    "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.

With those records, I'd like to make a JOIN between documents with "type": person and "type": prescription on value.id = value.patient.

我已经尝试了以下阶段的汇总:

I've already tried an aggregation with the following stages:

{
    "$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"},行.如果相反,我尝试使用双美元符号($$)(见此处 ),结果是错误Use of undefined variable: value.

But it produces an error FieldPath field names may not contain '.'. Which I believe is due to the "let": { "patient": "$value.id"}, line. If instead I try double dollar signs ($$) (as seen here), the result is the error Use of undefined variable: value.

关于如何进行聚合的任何想法?

Any idea of how I can make this aggregation?

推荐答案

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

Done with the following pipeline object inside the $lookup stage

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

这篇关于具有多个条件的Mongo 3.6聚合查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆