【问题标题】:$elemMatch with distinct$elemMatch 与不同的
【发布时间】:2018-12-13 08:21:58
【问题描述】:

我对不同的查询有一些问题。

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

我不想得到空字符串的结果。我尝试运行查询:

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

为什么我有空数组?我的错在哪里?

【问题讨论】:

  • 这应该工作 db.sessions.distinct('{"tests.device_serial":{$ne: ""}}');
  • db.sessions.distinct('{"tests.device_serial":{$ne: ""}}') [ ] 同样的问题。 MongoDB shell 版本 v3.6.3。
  • tests.device_serial 是一个数组吗?
  • 如果您发布示例数据会更好,因为从这里看起来没问题
  • @anthony-winzlet 看起来像这样 [{ "obj_lens_inspection_mask": 6, "tests": [{ "device_serial": "5acccdf25c089", "firmware_version": "3.1.00.121" }] }, {“obj_lens_inspection_mask”:3,“测试”:[{“device_serial”:“5acccdf25c57a”,“firmware_version”:“3.1.00.121”},{“device_serial”:“”,“firmware_version”:“”},{“ device_serial": "5acccdf25c5de", "firmware_version": "3.1.00.121" }] }]

标签: mongodb distinct


【解决方案1】:

猜测 tests.device_serial 是一个数组,这是你的错误:

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

distinct 命令中的查询正在过滤数组“tests”包含名为 device_serial 且值为 "" 的字段的文档,而不仅仅是数组中的字段。

要实现您想要的,您可以使用聚合框架,将数组展开到多个文档,使用 $addToSet 命令按 null 过滤和分组以获取不同的值。

这里是查询:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 2015-07-24
    • 2019-06-24
    • 1970-01-01
    • 2013-11-24
    相关资源
    最近更新 更多