我如何根据MongoDB中createdAt的日期添加文档值?
我需要添加一个值,该值存在于createdAt是当日的每个文档的“ value”属性中,该文档具有为true的“ finished”属性,并且该文档具有“ value”和“ period”。 check_out”属性。
到目前为止,我已经能够选择所有具有“ period.check_out”属性的文档并对其值求和。问题是选择当天的文件。我已经尝试通过多种方式按天排序,但是我没有得到。
我启用了nas数据库模型,因此无论何时创建新文档,它都会自动为我添加一个createdAt,updatedAt和_v。
文档示例:
[
{
"_id": "1",
"client": {
"name": "raul germano"
},
"parking": {
"_id": "5d8bfe395e0a822b143fd68d",
"value": 2.59,
"name": "pro parking oficial"
},
"finished": false,
"createdAt": "2019-09-25T23:54:32.802Z",
"updatedAt": "2019-09-25T23:54:32.802Z"
},
{
"_id": "2",
"client": {
"name": "raul vitor"
},
"parking": {
"_id": "5d8bfe395e0a822b143fd68d",
"value": 2.32,
"name": "pro parking oficial"
},
"period": {
"check_in": {
"user": "caboco",
"moment": "2019-09-25T00:05:36.273Z"
},
"check_out": {
"user": "outro caboco",
"moment": "2019-09-25T00:09:56.506Z"
}
},
"hours": 0.07,
"value": 0.17,
"finished": true,
"createdAt": "2019-09-26T23:54:33.463Z",
"updatedAt": "2019-09-26T23:54:33.463Z"
},
{
"_id": "3",
"client": {
"name": "raul germano"
},
"parking": {
"_id": "5d8bfe395e0a822b143fd68d",
"value": 2.60,
"name": "pro parking oficial"
},
"finished": true,
"createdAt": "2019-09-25T23:54:33.463Z",
"updatedAt": "2019-09-25T23:54:33.463Z",
"period": {
"check_in": {
"user": "caboco",
"moment": "2019-09-25T00:05:36.273Z"
},
"check_out": {
"user": "outro caboco",
"moment": "2019-09-25T00:09:56.506Z"
}
},
"hours": 0.09,
"value": 0.23
}
]
当前查询:
collection.aggregate([
{
$match: {
'period.check_out': {
$exists: true
},
createdAt: {
$gte: new Date("2019-09-24")
$lt: new Date("2019-09-25")
}
}
},
{
$unwind: '$parking'
},
{
$match: {
'parking._id': Types.ObjectId(parking_id)
}
},
{
$group: {
_id: Types.ObjectId(parking_id),
total: {
$sum: '$value'
}
}
}
])
这样,他选择了最近的24小时
根据上述文档,我只需要选择_id“ 1”和“ 2”文档。由此产生
回答如下:考虑到当前日期为'2019-09-26',请尝试使用以下内容替换$ match:
{
$match: {
'period.check_out': {
$exists: true
},
createdAt: {
$gte: new Date('2019-09-26'),
$lte: new Date(),
}
}
},
您要匹配的是:$ gte:2019-09-24T00:00:00.000Z,$ lte:2019-09-25T00:00:00.000Z。我认为那不是当前日期。相反,您需要匹配的是'2019-09-24T00:00:00.000Z'-当前时间。