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
The $pull operator removes from an existing array all instances of a value or values that match a specified condition.
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 .
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, );
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.
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?
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With