How to replace an element in an array field in mongodb

北城余情 提交于 2019-12-12 05:32:21

问题


Field tags is array in scenes document. I wanna replace element 'Bad' with 'Good' in the array as:

db.scenes.update({ 'tags': 'Bad' }, { $set: { 'tags.$' : 'Good' } }, { 'multi':true});

I don't know how to do it in doctrine. I tried

    $dm->createQueryBuilder('SceneBundle:Scene')
        ->update()
        ->field('tags.$')->set($tag)
        ->field('tags')->equals($oldTag)
        ->multiple(true)
        ->getQuery()
        ->execute();

but not work.

Thanks.


回答1:


There isn't a single replace function for this, but you can do it in one query by pulling all the 'Bad' out, and pushing 'Good' in

db.scenes.update({ 'tags': 'Bad' }, { $pull: { 'tags' : 'Bad' }, $push: { 'tags' : 'Good' } }, { 'multi':true});

The doctrine equivalent should be :

 $dm->createQueryBuilder('SceneBundle:Scene')
    ->update()
    ->field('tags')->pull('Bad')
    ->field('tags')->push('Good')
    ->field('tags')->equals('Bad')
    ->multiple(true)
    ->getQuery()
    ->execute();

Refer to the doctrine docs here : http://docs.doctrine-project.org/projects/doctrine-mongodb-odm/en/latest/reference/query-builder-api.html




回答2:


it's been a long time, but just to not leave this post without a good answer I found a link (Mongodb array $push and $pull) which can help us.

The issue is that MongoDB doesn’t allow multiple operations on the same property in the same update call. This means that the two operations must happen in two individually atomic operations.



来源:https://stackoverflow.com/questions/15975219/how-to-replace-an-element-in-an-array-field-in-mongodb

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