在mongoDB上具有依赖条件的聚合 [英] Aggregations with dependent conditions on mongoDB

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

问题描述

我想找到那些鼻子过敏然后鼻子癌的患者。

I want to find those patients who he/she had got nose allergic then got nose cancer.

因此以下数据应返回用户 Jack

So the following data should return the user Jack.

Jack 满足查询条件。

请给我一些类似的查询,类似于此类问题。非常感谢

Please give me some similar queries are similar to this kind of problem. Thanks so much

{
    "id": 1,
    "name": "Mary",
    "symptoms": "nose allerge",
    "datetime": "2011-04-02"
},

{
    "id": 2,
    "name": "Jack",
    "symptoms": "nose allerge",
    "datetime": "2011-04-02"
},

{
    "id": 3,
    "name": "Mark",
    "symptoms": "nose allerge",
    "datetime": "2010-01-02"
},

....


{
    "id": 4,
    "name": "Jack",
    "symptoms": "nose cancer",    
    "datetime": "2015-04-09"
},

{
    "id": 5,
    "name": "Mary",
    "symptoms": "nose cancer",    
    "datetime": "2010-09-02"
},


推荐答案

尝试以下聚合管道,该管道首先针对有问题的两种症状过滤文档,然后根据 datetim在下一个管道中对生成的文档进行排序e 降序,然后可以按名称进行分组,并将那些有序的症状推入数组诊断。然后,通过匹配值 nose carcinoma 的第一个诊断数组元素,进一步过滤来自先前分组管道的结果文档,因为那应该是最新的症状,然后第二个元素是鼻子融合 。您终于可以通过 $ project 操作使您的患者得到:

Try the following aggregation pipeline which first filters documents on the two symptoms in question, then sorts the resulting documents in the next pipeline by datetime descending which can then be grouped by name and get those ordered symptoms pushed to an array diagnosis. You then further filter the resulting documents from the previous grouping pipeline by matching on the first diagnosis array element that has value "nose cancer" because that should be the latest symptom and with then second element being "nose allerge". You finally have your patient through $project operation:

db.collection.aggregate([
    {
        $match: {
            symptoms: { $in: ["nose allerge", "nose cancer"] }
        }
    },
    {
        $sort: { datetime: -1 }
    },/**/
    {
        $group: {
            _id: "$name",
            "diagnosis": { 
                "$push": "$symptoms" 
             }
        }
    },
    {
        $match: {
            "diagnosis.0": "nose cancer",
            "diagnosis.1": "nose allerge"
        }
    },
    {
        $project: {
            name: "$_id",
            symptoms: "$diagnosis",
            _id: 0
        }
    }
])

结果:

{
    "result" : [ 
        {
            "name" : "Jack",
            "symptoms" : [ 
                "nose cancer", 
                "nose allerge"
            ]
        }
    ],
    "ok" : 1.0000000000000000
}

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

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