Mongodb 基于日期查询的嵌套数组中的更新可能无法正常工作(或者我做错了…)
创建集合“测试”,并在其中插入一个文档:Mongodb 基于日期查询的嵌套数组中的更新可能无法正常工作(或者我做错了…),mongodb,mongodb-query,Mongodb,Mongodb Query,创建集合“测试”,并在其中插入一个文档: { "_id" : NumberLong(1), "pointsBalances" : [ { "period" : "2020", "startDate" : ISODate("2020-01-01T00:00:00.000Z"), "endDate" : ISODate("2020-12-31T23:59:59.999Z"),
{
"_id" : NumberLong(1),
"pointsBalances" : [
{
"period" : "2020",
"startDate" : ISODate("2020-01-01T00:00:00.000Z"),
"endDate" : ISODate("2020-12-31T23:59:59.999Z"),
"value" : 0
},
{
"period" : "2019",
"startDate" : ISODate("2019-01-01T00:00:00.000Z"),
"endDate" : ISODate("2019-12-31T23:59:59.999Z"),
"value" : 0
}
]
}
然后请执行更新-它应能正常工作:
db.getCollection('test').update(
{$and: [ {'_id': 1}, {"pointsBalances.period": '2019'}]},
{$set: { "pointsBalances.$.value": 100 } }
)
现在,让我们尝试根据日期进行更新:
db.getCollection('test').update(
{ $and: [
{'_id': 1},
{"pointsBalances.startDate": {$lte: ISODate("2019-05-01T00:00:00.000Z")}},
{"pointsBalances.endDate": {$gte: ISODate("2019-05-01T00:00:00.000Z")}}
]},
{$set: { "pointsBalances.$.value": 200 } })
似乎更新了错误的元素MongoDB将第一个匹配的文档更新为条件,请尝试elemMatch
db.michel.update(
{ $and: [
{'_id': 1},
{"pointsBalances" : {
"$elemMatch" : { $and: [
{"startDate": {$lte: ISODate("2019-05-01T00:00:00.000Z")}},
{"endDate": {$gte: ISODate("2019-05-01T00:00:00.000Z")}}
]}}}]},
{$set: { "pointsBalances.$.value": 200 } });
嗨,Priyanka Kariya,谢谢你的建议,但对于最新情况,我的解决方案也有效。当我们还有结束日期的条件时,问题就出现了。elementMatch似乎没有改变任何东西:(