这是生成的查询:mongo.update({...}, {$set: {'strs.$.nds.title': 'new-title'}})这就是 mongo 抛出异常的原因,说它不能在数组中创建 title 字段.我这样做错了吗?因为 MongoTemplate 正在生成一个无效的查询,该查询失败(显然). 解决方案 你能做的是update.set("strs.$[elmStr].nds.$[elmNds].title", title).filterArray("elmStr._id", strsId).filterArray("elmNds._id",ndsId);并参考位置运算符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). 解决方案 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 这篇关于Spring-Mongo-Data Update 只允许一个位置参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
11-02 15:45