首页 > 解决方案 > MongoDB - 仅在日期时间中使用 $lte 数小时

问题描述

我的数据如下所示:

/* 1 */
{
    "_id" : ObjectId("5b62f97e3c2094eefa912aba"),
    "FietsID" : 1267,
    "Stad" : "Antwerpen",
    "Accelerometer" : 1.0,
    "Decibel" : null,
    "Datum" : ISODate("2017-06-06T05:45:06.000Z"),
    "Location" : {
        "type" : "Point",
        "coordinates" : [ 
            22.50891, 
            48.54121
        ]
    }
}

/* 2 */
{
    "_id" : ObjectId("5b62f97e3c2094eefa9128cc"),
    "FietsID" : 1971,
    "Stad" : "Antwerpen",
    "Accelerometer" : 1.0,
    "Decibel" : 55,
    "Datum" : ISODate("2017-06-11T18:17:21.000Z"),
    "Location" : {
        "type" : "Point",
        "coordinates" : [ 
            -38.23146, 
            -6.75194
        ]
    }
}

我想获取时间低于 06:00:00、分贝高于 90 且仅安特卫普“Stad”的所有数据

我尝试使用聚合$dateToString,但似乎我只能使用 1 个参数进行匹配。

标签: mongodbaggregation-framework

解决方案


您可以使用$expr3.6 中提供的运算符在查找查询中使用聚合运算符并$and包含所有条件。

用于$hour从日期获取小时。

就像是

db.colname.find
({"$expr":{
  "$and":[
    {"$lte":[{"$hour":"$Datum"},6]},
    {"$gt":["$Decibel",90]},
    {"$gt":["$Stad","Antwerpen"]}
  ]
}})

推荐阅读