【问题标题】:Limit distinct values only if a subelement exists仅当存在子元素时才限制不同的值
【发布时间】:2019-07-19 14:38:54
【问题描述】:

我在这里搜索过,但找不到以下问题的明确答案。在下面的示例集合mycollection 中,如何在存在status 字段且statusUNLOCKED 的对象中选择不同的vin 数字only

我试过了

db.getCollection('mycollection').distinct("vin",  {$and: [{"decoded_payload.status": {$exists: true}}, {"decoded_payload.status":"UNLOCKED"}]})

但是这个查询会无限期挂起

由于数据库的大小和此类查询的长时间延迟,我想限制输出以检查它是否完全运行,但似乎limit() 不是.distinct() 的选项

在 MongoDB 中,如何在下面的数据中选择不同的 vin,设置 limit = 1 并仅根据 status 条件(status 存在并且等于“UNLOCKED”)进行选择?

aggregate() 会是正确的选择吗?如何将上述条件与aggregate()limit() 一起使用?

这种情况下的输出将是 34567

{
    "_id" : ObjectId("1"),
    "vin" : "12345",
    "class_name" : "foo",
    "decoded_payload" : {
        "timestamp" : 1547329250,
        "status" : "LOCKED"
    }
}
{
    "_id" : ObjectId("2"),
    "vin" : "23456",
    "class_name" : "foo",
    "decoded_payload" : {
        "timestamp" : 1547329260,
        "status" : "LOCKED"
    }
}
{
    "_id" : ObjectId("3"),
    "vin" : "34567",
    "class_name" : "bar",
    "decoded_payload" : {
        "timestamp" : 1547329270,
        "status" : "UNLOCKED",
        "reservation_id" : "71"

    }
}
{
    "_id" : ObjectId("4"),
    "vin" : "45678",
    "class_name" : "baz",
    "decoded_payload" : {
        "timestamp" : 1547329280,
        "reservation_id" : "71"

    }
}    

【问题讨论】:

    标签: mongodb mongoose nosql mongodb-query


    【解决方案1】:

    您可以使用此聚合查询来过滤数据并返回不同的“vin”

    db.mycollection.aggregate([
        {
            $match: {
                $and: [{
                        "decoded_payload.status": { $exists: true }
                       }, {
                        "decoded_payload.status": "UNLOCKED"
                }]
            }
        },
        { $limit : 5 }, // You can use this stage after group too
        {
            $group: { _id: "$vin" }
        }
    ])
    

    根据要求在$group阶段之前和之后使用限制阶段

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-20
      • 1970-01-01
      • 1970-01-01
      • 2021-05-06
      • 1970-01-01
      • 1970-01-01
      • 2021-11-16
      相关资源
      最近更新 更多