$elemMatch with distinct

时光总嘲笑我的痴心妄想 提交于 2019-12-24 17:13:43

问题


I have some problems with distinct queries.

db.sessions.distinct("tests.device_serial")
[
        "",
        "5b34f4bf9854a",
        "5b34f4bf98664",
        "5b34f4bf98712",
        "5b34f4bf9876b",
        "5b34f4bf987c6"
]

I don't want to get the result with empty strings. I tried to run query:

 db.sessions.distinct("tests.device_serial", {"tests.device_serial" : {$ne: ""}})
[ ]

Why I got empty array? Where is my mistake?


回答1:


Guessing tests.device_serial is an array, here's your mistake :

 db.sessions.distinct("tests.device_serial", {"tests.device_serial" : {$ne: ""}})

Query in your distinct command is filtering documents where the array 'tests' contains a field named device_serial with a value of "", and not only the fields in array.

To achieve what you want, you can use aggregation framework, unwind array to multiple documents, filter and group by null with an $addToSet command to get distinct values.

Here's the query :

db.sessions.aggregate(
    [
        {
            $unwind: {
                path : "$tests"
            }
        },
        {
            $match: {
            "tests.device_serial":{$ne:""}
            }
        },
        {
            $group: {
              "_id":null,
                "device_serials":{$addToSet:"$tests.device_serial"}
            }
        },
    ]
);


来源:https://stackoverflow.com/questions/51181355/elemmatch-with-distinct

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!