3

The document structure looks like below -

{
    "nestedDocArray" : [ 
        {
            "a" : "a",
            "b" : "b",
            "c" : "c",
            "createdOn" : ISODate("2018-06-19T08:38:34.228Z")
        }, 
        {
            "a" : "a1",
            "b" : "b1000",
            "c" : "c1",
            "createdOn" : ISODate("2018-06-19T08:38:34.233Z")
        }, 
        {
            "a" : "a1000",
            "b" : "b1000",
            "c" : "c1000",
            "createdOn" : ISODate("2018-06-21T10:54:30.679Z")
        }
    ]
}

If I try to do a $push, $pull and $set on the same nestedDocArray attribute in a single update statement, it results in the exception "Updating the path 'nestedDocArray' would create a conflict at 'nestedDocArray'"

  • 2
    You cannot do `$pull` and `$push` for the same **array** in a single update query of mongodb... You will have to use different query to do this operation – Ashh Jun 21 '18 at 17:50
  • Since mongodb doesn't have transaction management, this leaves me with not too many options since my business logic requires me to $pull and $push or none at all. Is there any other way to achieve this? – Vidya Ramanarayanan Jun 22 '18 at 06:54
  • You have only option left i.e. to use two queries... One for `$pull` and one for `$push` – Ashh Jun 22 '18 at 07:38
  • Does this answer your question? [Mongodb array $push and $pull](https://stackoverflow.com/questions/34217874/mongodb-array-push-and-pull) – Jacob Sep 16 '22 at 05:53

1 Answers1

1

I know the answer is too late, but it can.

db.collection.updateOne({'array.field':'value'}, //finding(matching)

    [ //start of update pipeline
  
      { $set:{'array.isValid':false}}, //set every element => isValid = false 

      { $set: { array: { $concatArrays: [ "$array", [ newElem1, newElem2]]}}} //push set

    ] //end of update pipeline

);
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Mohab
  • 11
  • 1
  • 2