errmsg" : "无法从 BSON 类型字符串转换为 Date
errmsg" : "can't convert from BSON type string to Date
我正在尝试按给定年份的月份和年份汇总销售额总和。所以我遵循文档以及其他人使用此代码所做的事情:
`db.sales.aggregate([{$project: {year: {$year: "saleDate"}, month: {$month: "saleDate"}, dayOfMonth:
{$dayOfMonth: "saleDate"}}}, {$group: {_id: {year: '$year', month: '$month'},
count: {$sum: 1}}}]);
但是 returns 错误:
"errmsg" : "can't convert from BSON type string to Date"
我不明白为什么 Compass 中的模式说它是 "date" 类型。
我尝试了一种我见过的使用 'new Date' 函数完成的不同方式,但我没有收到任何错误,但没有结果。我不知道如何使用 mongo[ 中的日期=13=]
`db.sales.aggregate([{$match: {'saleDate': {$gte: {$dayOfYear: new Date("2017-06-01")},
$lt: {$dayOfYear: new Date("2017-07-01")}}}},
{$group: {_id: { 'numberofSales': {$sum: 1}}}}])
您的第一个查询的问题是您缺少美元符号并且 MongoDB 将 saleDate
视为硬编码 string 而不是 $saleDate
将被视为 字段参考 ,尝试:
db.sales.aggregate([{$project: {year: {$year: "$saleDate"}, month: {$month: "$saleDate"}, dayOfMonth:
{$dayOfMonth: "$saleDate"}}}, {$group: {_id: {year: '$year', month: '$month'},
count: {$sum: 1}}}]);
更多here
您的第二个查询将不起作用,因为您正试图将 $dayOfYear 返回的数字与日期字段进行比较。
我正在尝试按给定年份的月份和年份汇总销售额总和。所以我遵循文档以及其他人使用此代码所做的事情:
`db.sales.aggregate([{$project: {year: {$year: "saleDate"}, month: {$month: "saleDate"}, dayOfMonth:
{$dayOfMonth: "saleDate"}}}, {$group: {_id: {year: '$year', month: '$month'},
count: {$sum: 1}}}]);
但是 returns 错误:
"errmsg" : "can't convert from BSON type string to Date"
我不明白为什么 Compass 中的模式说它是 "date" 类型。
我尝试了一种我见过的使用 'new Date' 函数完成的不同方式,但我没有收到任何错误,但没有结果。我不知道如何使用 mongo[ 中的日期=13=]
`db.sales.aggregate([{$match: {'saleDate': {$gte: {$dayOfYear: new Date("2017-06-01")},
$lt: {$dayOfYear: new Date("2017-07-01")}}}},
{$group: {_id: { 'numberofSales': {$sum: 1}}}}])
您的第一个查询的问题是您缺少美元符号并且 MongoDB 将 saleDate
视为硬编码 string 而不是 $saleDate
将被视为 字段参考 ,尝试:
db.sales.aggregate([{$project: {year: {$year: "$saleDate"}, month: {$month: "$saleDate"}, dayOfMonth:
{$dayOfMonth: "$saleDate"}}}, {$group: {_id: {year: '$year', month: '$month'},
count: {$sum: 1}}}]);
更多here
您的第二个查询将不起作用,因为您正试图将 $dayOfYear 返回的数字与日期字段进行比较。