【问题标题】:Can't convert from BSON type string to Date on aggregation pipeline无法在聚合管道上从 BSON 类型字符串转换为日期
【发布时间】:2018-03-20 00:00:50
【问题描述】:

我正在使用 MongoDB 3.4.9,并且我希望获得 w.r.t 的月度报告。客户信息,这里是带有嵌套项目和收到错误的示例 mongodb 记录:

无法从 BSON 类型字符串转换为日期

    {
"_id" : ObjectId("59da6a331c7a9ac0b6674fe8"),
"date" : ISODate("2017-10-08T18:10:59.899Z"),
"items" : [ 
    {
        "quantity" : 1,
        "price" : 47.11,
        "desc" : "Item #1"
    }, 
    {
        "quantity" : 2,
        "price" : 42.0,
        "desc" : "Item #2"
    }
],
"custInfo" : "Tobias Trelle, gold customer"
  }

{
"_id" : ObjectId("59da6a511c7a9ac0b6674fed"),
"date" : ISODate("2017-10-08T18:11:28.961Z"),
"items" : [ 
    {
        "quantity" : 1,
        "price" : 47.11,
        "desc" : "Item #1"
    }, 
    {
        "quantity" : 2,
        "price" : 42.0,
        "desc" : "Item #2"
    }
],
"custInfo" : "Tobias Trelle, gold customer"
  }

  {
"_id" : ObjectId("59da6a511c7a9ac0b6674ff0"),
"date" : ISODate("2017-10-08T18:11:29.133Z"),
"items" : [ 
    {
        "quantity" : 1,
        "price" : 47.11,
        "desc" : "Item #1"
    }, 
    {
        "quantity" : 2,
        "price" : 42.0,
        "desc" : "Item #2"
    }
],
"custInfo" : "Tobias Trelle, gold customer"
  }

这是 MongoDB 查询,用于按 custInfo 按月计算总和分组

db.runCommand({aggregate:"order", pipeline : 
[{$match : {$and : [{"date" : {$gte : ISODate("2016-10-08T18:10:59.899Z")}},
{"date" : {$lte : ISODate("2018-10-08T18:10:59.899Z")}}]}}
, 
{ "$project" : { "custInfo" : 1 ,"count" : 1 ,   "date" : 1 , 
"duration" : {"$month" : [ "date"]}}},
{ "$group" : { "_id" : 
    { "duration" : "$duration" , "custInfo" : "$custInfo"} ,"count" : { "$sum" : 1} }}

    ]}//,
    //cursor:{batchSize:1000}

 )

请帮忙看看我哪里错了。

问候 克里斯

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    与您的具体情况无关,但与此 BSON 错误的通用解决方案有关... 解决这个问题:

    {"project: { "y.dateFieldName":
     {"$cond":[{ $eq: [{$type: "$data.dateFieldName"},'date']},{"$year":"$data.dateFieldName"},-1]}}
    

    【讨论】:

      【解决方案2】:

      我不确定为什么 $month 在这里被认为是“持续时间”,但无论如何,您从字段变量中删除了一个美元符号,并且对 $month 的调用有点不对劲。这应该有效:

      { "$project" : { "custInfo" : 1 ,
                   "count" : 1 ,
                   "date" : 1 ,
                   "duration" : {"$month" : "$date" } }}
      

      【讨论】:

        猜你喜欢
        • 2017-11-04
        • 2021-03-22
        • 2017-09-23
        • 2018-05-24
        • 2019-11-29
        • 2013-01-25
        • 2015-04-09
        • 2017-06-17
        相关资源
        最近更新 更多