我有一个看起来像这样的模式:
var Counter = new Schema ({
_id: ObjectId,
date: Date,
counter: Number
})
根据要求,我发送一天的日期,并期望添加日期,并且计数器增加。现在,当我添加时,计数器将增加,即1、2、3等,并添加日期。
现在这是一个问题:我希望在给定不同日期时将计数器重置为0(例如,在每个新的一天,计数器应从0开始),然后再次开始计数器递增等等...
这是我如何尝试的代码:
Counter.findOneAndUpdate(
{
$set:{
"date: thedate",
},
$inc: {
"counter: counter+1"
}
)
我该如何实现?
我仍然不清楚您要实现什么,但是您可以通过中断查找和更新来尝试此方法
Counter.findOne({}) //match inside {} condition
.then(counter => {
if(counter.date){ //apply date condition here
counter.counter+=1;
} else {
counter.counter = 0;
}
counter.save()
.then(updatedCounter => {
// further action you want to take
})
})
.catch(err => {
//handle err here
})
由于您可以从MongoDB版本> = update-with-an-aggregation-pipeline开始的.update()
操作中执行4.2
,请尝试以下查询:
Counter.updateMany(
{ _id: ObjectId("............") }, // filter query - Input of type ObjectId()
/** Update date field with input & re-create 'counter' field based on condition */
[{
$addFields: {
date: inputDate, // Input type of date, In general Date is saved in MongoDB as ISODate("2020-05-06T00:00:00.000Z")
counter: { $cond: [ { $eq: [ "$date", inputDate ] }, { $add: [ "$counter", 1 ] }, 0 ] }
}
}]
)
Test:在此处测试聚合管道:mongoplayground
注意:如果发现使用.updateMany()
执行这些查询时遇到任何问题,请尝试使用带有选项.update()
的{ multi : true }
。