1

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.

K1Zhang
  • 93
  • 2
  • 4
  • I don't know about doctrine, but here's [how to replace an array element in MongoDB](https://stackoverflow.com/questions/48545448/mongodb-replace-specific-array-values). – Dan Dascalescu Jun 02 '20 at 04:17

2 Answers2

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.

Community
  • 1
  • 1
Marabesi
  • 94
  • 1
  • 6
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

Adil
  • 2,092
  • 3
  • 25
  • 35
  • No, this does not work. I wrote this at first and mongod complained:`code`(Field name duplication not allowed with modifiers) – K1Zhang Apr 12 '13 at 23:47
  • huh, probably three. Need find documents to be modified first – K1Zhang Apr 13 '13 at 00:01
  • It doesn't need to be done twice in mongo. However, I'm not fluent with Doctrine to give you an answer. Try some options and post the answer here. – Adil Apr 13 '13 at 14:59
  • This don't woks for me... `errmsg: 'exception: Cannot update \'tags\' and \'tags\' at the same time` – Aral Roca Sep 13 '15 at 12:09