MongoDB: 聚合查询未在函数内部传递值
MongoDB: Aggregate query is not passing value inside the function
我遇到了 Mongoose 聚合查询问题。我有以下模式,它是一个对象数组并包含 endDate
值。
[
{
"id": 1,
"endDate": "2022-02-28T19:00:00.000Z"
},
{
"id": 2,
"endDate": "2022-02-24T19:00:00.000Z"
},
{
"id": 3,
"endDate": "2022-02-25T19:00:00.000Z"
}
]
所以,在聚合结果的时候,我要添加一个新的字段名isPast
,它包含了布尔值,并进行计算来检查endDate
是否通过。如果已经通过,那么 isPast
将是 true
否则 false
.
我正在使用 returns 布尔值的 moment 库中的 isBefore
函数。但是在这个函数内部面临着关于传递 endDate
值的问题。 $endDate
作为字符串传递,而不是值。
有没有办法在函数内部传递endDate的值?
const todayDate = moment(new Date()).format("YYYY-MM-DD");
db.collection.aggregate([
{
$addFields: {
"isPast": moment('$endDate', 'YYYY-MM-DD').isBefore(todayDate)
},
},
])
不用momentjs也能实现。使用 $toDate
将 date-time 字符串转换为日期
db.collection.aggregate([
{
$addFields: {
"isPast": {
$gt: [
new Date(),
{
$toDate: "$endDate"
}
]
}
}
}
])
如果您只想比较日期:
db.collection.aggregate([
{
$set: {
"currentDate": "$$NOW",
"endDate": {
$toDate: "$endDate"
}
}
},
{
$addFields: {
"isPast": {
$gt: [
{
"$dateFromParts": {
"year": {
$year: "$currentDate"
},
"month": {
$month: "$currentDate"
},
"day": {
"$dayOfMonth": "$currentDate"
}
}
},
{
"$dateFromParts": {
"year": {
$year: "$endDate"
},
"month": {
$month: "$endDate"
},
"day": {
"$dayOfMonth": "$endDate"
}
}
}
]
}
}
}
])
我遇到了 Mongoose 聚合查询问题。我有以下模式,它是一个对象数组并包含 endDate
值。
[
{
"id": 1,
"endDate": "2022-02-28T19:00:00.000Z"
},
{
"id": 2,
"endDate": "2022-02-24T19:00:00.000Z"
},
{
"id": 3,
"endDate": "2022-02-25T19:00:00.000Z"
}
]
所以,在聚合结果的时候,我要添加一个新的字段名isPast
,它包含了布尔值,并进行计算来检查endDate
是否通过。如果已经通过,那么 isPast
将是 true
否则 false
.
我正在使用 returns 布尔值的 moment 库中的 isBefore
函数。但是在这个函数内部面临着关于传递 endDate
值的问题。 $endDate
作为字符串传递,而不是值。
有没有办法在函数内部传递endDate的值?
const todayDate = moment(new Date()).format("YYYY-MM-DD");
db.collection.aggregate([
{
$addFields: {
"isPast": moment('$endDate', 'YYYY-MM-DD').isBefore(todayDate)
},
},
])
不用momentjs也能实现。使用 $toDate
将 date-time 字符串转换为日期
db.collection.aggregate([
{
$addFields: {
"isPast": {
$gt: [
new Date(),
{
$toDate: "$endDate"
}
]
}
}
}
])
如果您只想比较日期:
db.collection.aggregate([
{
$set: {
"currentDate": "$$NOW",
"endDate": {
$toDate: "$endDate"
}
}
},
{
$addFields: {
"isPast": {
$gt: [
{
"$dateFromParts": {
"year": {
$year: "$currentDate"
},
"month": {
$month: "$currentDate"
},
"day": {
"$dayOfMonth": "$currentDate"
}
}
},
{
"$dateFromParts": {
"year": {
$year: "$endDate"
},
"month": {
$month: "$endDate"
},
"day": {
"$dayOfMonth": "$endDate"
}
}
}
]
}
}
}
])