wangming1993 / issues

记录学习中的一些问题,体会与心得 https://wangming1993.github.io/issues
8 stars 4 forks source link

一组复杂的mongodb查询操作 #28

Open wangming1993 opened 8 years ago

wangming1993 commented 8 years ago

_member_ 的结构如下:

db.member.insert(
{
    "name": "mike5",
    "socials": [
        {
            "channel": "123",
            "openId": "12"
        },
       {
            "channel": "124",
            "openId": "12"
        }
    ],
}
);

 查询要求

查找出member中socials中channel和openId重复的数据

db.member.aggregate(
    [
        {
            "$match": {
                "socials": {
                    "$elemMatch": {
                        "channel": "123"
                    }
                }
            }
        },
        {
            "$unwind": "$socials"
        },
        {
            "$group": {
                "_id":{
                    "channel": "$socials.channel",
                    "openId": "$socials.openId"
                },
                "count": {
                    "$sum": 1
                }
            }
        },
        {
            "$match": {
                "count": {
                    "$gt": 1
                }
            }
        }
    ]
);