【问题标题】:MongoDB Aggregation : Date Comparison in Filter not workingMongoDB聚合:过滤器中的日期比较不起作用
【发布时间】:2020-10-27 17:46:39
【问题描述】:

我需要使用以下方法在一天内处理日志和订单:

但如果我使用 $eq 结果总是返回空。但是如果我使用 $gte 进行日期比较($$order.LogDate),那么我会得到订单数。但匹配的数据在数据库中可用。知道我在哪里做错了吗?我还尝试将 $gte 和 $lte 与日期和日期 + 1 天一起使用。仍然没有运气:

{ 
  "_id" : 0,
   "FirstName" : { "$arrayElemAt" : ["$drivers.FirstName", 0] },
   "LastName" : { "$arrayElemAt" : ["$drivers.LastName", 0] },
   "PhoneNumber" : { "$arrayElemAt" : ["$drivers.ContactNo", 0] },
    "LogDate" : "$_id.LogDate",
    "LogDateEnd":{ $add: [ "$_id.LogDate", 86400000 ] },
    "TotalMinutes" : "$TotalMinutes", 
    "OrderCount" : { 
            "$size" : {
               "$filter" : { 
                 "input" : "$orders", 
                 "as":"order",
                 "cond" : { 
                   "$and" : [{ "$eq" : ["$$order.OrderStatus", "COMPLETE"] },{ "$eq" : ["$$order.LogDate", "$LogDate"] }] 
                   } 
                 } 
               } 
            } 
    }

【问题讨论】:

  • 您能给我们看一个示例文档或可重现的场景吗?

标签: mongodb aggregation-framework


【解决方案1】:

当您比较日期时,除非它们相同,否则不会发生匹配。

ISODate("2018-07-05T07:14:59.191+0000")
ISODate("2018-07-05T07:14:59.192+0000")

即使这些日期实际上相同,但 1 毫秒的差异足以使 $eq 运算符返回 false。

如果您想要某一天的所有orders。您所要做的就是使用像 $dayOfMonth 这样的日期表达式进行匹配,如下所示:

"OrderCount": {
    "$size": {
        "$filter": {
            "input": "$orders",
            "as": "order",
            "cond": {
                "$and": [
                    {"$eq": ["$$order.OrderStatus", "COMPLETE"]},
                    {"$eq": [{$year: "$$order.LogDate"}, {$year: "$LogDate"}]},
                    {"$eq": [{$month: "$$order.LogDate"}, {$month: "$LogDate"}]},
                    {"$eq": [{$dayOfMonth: "$$order.LogDate"}, {$dayOfMonth: "$LogDate"}]}
                ]
            }
        }
    }
}

这将从$logDate所在的一年中的那一天开始留下订单。

【讨论】:

  • 嗨,当将 $LogDate 传递给 $and 或内部时,我收到以下错误“”errmsg”:“无法从缺少的 BSON 类型转换为日期”,“
  • 我只是假设logDatedate 类型字段,但此错误表明不是,您应该使用您拥有的date 字段(LogDateEnd?)。
  • 其实LogDate是一个ISODate类型
  • "BSON type missing",即该字段丢失。无论哪种方式,它都不是 date 类型。
  • 感谢您的帮助。问题是我必须传递“_id.LogDate”而不是上面的计算值 LogDate。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-14
  • 2019-09-23
  • 2015-12-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多