Spring-Mongo-Data Update only allows one positional argument?

淺唱寂寞╮ 提交于 2021-01-28 05:17:38

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!