创建集合“测试”,然后将一个文档插入其中:
{
"_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 } })
似乎错误的元素已更新
答案 0 :(得分:1)
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 } });