Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb array $push and $pull

Tags:

mongodb

I was looking to pull some value from array and simultaneously trying to update it.

    userSchema.statics.experience = function (id,xper,delet,callback) {     var update = {       $pull:{         'profile.experience' : delet       },          $push: {           'profile.experience': xper         }   };   this.findByIdAndUpdate(id,update,{ 'new': true},function(err,doc) {     if (err) {       callback(err);     } else if(doc){       callback(null,doc);     }   }); }; 

i was getting error like:

MongoError: exception: Cannot update 'profile.experience' and 'profile.experience' at the same time

like image 508
santhosh Avatar asked Dec 11 '15 07:12

santhosh


People also ask

What does $Pull do in MongoDB?

The $pull operator removes from an existing array all instances of a value or values that match a specified condition.

What is $Push in MongoDB?

If the field is absent in the document to update, $push adds the array field with the value as its element. If the field is not an array, the operation will fail. If the value is an array, $push appends the whole array as a single element. To add each element of the value separately, use the $each modifier with $push .

How do I pull an array of objects in MongoDB?

To remove object from array with MongoDB, we can use the $pull operator. db. mycollection. update({ '_id': ObjectId("5150a1199fac0e6910000002") }, { $pull: { items: { id: 23 } } }, false, true, );

How do I push an array in MongoDB?

In MongoDB, the $push operator is used to appends a specified value to an array. If the mentioned field is absent in the document to update, the $push operator add it as a new field and includes mentioned value as its element. If the updating field is not an array type field the operation failed.


2 Answers

I found this explanation:

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.

And you can read that posts:

Pull and addtoset at the same time with mongo

multiple mongo update operator in a single statement?

like image 149
Vladislav Kievski Avatar answered Sep 17 '22 11:09

Vladislav Kievski


In case you need replace one array value to another, you can use arrayFilters for update.

(at least, present in mongo 4.2.1).

db.your_collection.update(     { "_id": ObjectId("your_24_byte_length_id") },     { "$set": { "profile.experience.$[elem]": "new_value" } },     { "arrayFilters": [ { "elem": { "$eq": "old_value" } } ], "multi": true } )  

This will replace all "old_value" array elements with "new_value".

like image 21
Nikolay Prokopyev Avatar answered Sep 19 '22 11:09

Nikolay Prokopyev