问题
I have a data model with the following structure:
{
_id: ObjectId(''),
strs: [
{
_id: ObjectId(''),
nds: [
{
_id: ObjectId(''),
title: ''
},
.
.
.
]
},
.
.
.
]
}
Following query works perfectly fine in mongo
shell:
mongo.update({_id: ObjectId(''), 'strs._id': ObjectId(''), 'strs.nds._id': ObjectId('')}, {$set: {'strs.$.nds.$.title': 'new-title'}})
I am trying to do the same in Spring Boot, I have written the following lines of code:
Criteria criteria = new Criteria();
criteria.addOperator(Criteria.where("id").is(id),
Criteria.where("strs.id").is(strsId), Criteria.where("strs.nds.id", ndsId));
Query query = new Query().addCriteria(criteria);
Update update = new Update();
update.set("strs.$.nds.$.title", title);
mongoTemplate.findAndModify(query, update, MyModel.class);
But, this is not working as expected. It's saying that mongo
cannot create a title
field inside [nds: {...}]
. So, I logged the queries MongoTemplate
was generating, and it turns out that MongoTemplate
was removing the second positional argument $
from the query.
This was the generated query:
mongo.update({...}, {$set: {'strs.$.nds.title': 'new-title'}})
And this was the reason mongo
was throwing an exception saying it cannot create a title
field in an array.
Am I doing this wrong? Because MongoTemplate
is generating an invalid query which is failing (obviously).
回答1:
What you can do is
update.set("strs.$[elmStr].nds.$[elmNds].title", title)
.filterArray("elmStr._id", strsId)
.filterArray("elmNds._id",ndsId);
And refer positional operator
来源:https://stackoverflow.com/questions/61475499/spring-mongo-data-update-only-allows-one-positional-argument