无法将BSON类型字符串转换为聚合管道上的Date

时间:2017-10-08 19:30:00

标签: mongodb

我正在使用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"
  }

以下是按月custInfo计算总和分组的MongoDB查询

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}

 )

请在我错的地方帮忙。

此致 克里斯

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

与您的具体情况无关,但与解决此BSON错误的通用解决方案... 使用以下方法解决此问题:

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