Update element in array, if else exists, insert new element into this array in MongoDb

I have a group of array elements in MongoDB, as shown below:

{ "_id" : 5, "quizzes" : [ { "wk" : 1, "score" : 10 }, { "wk" : 2, "score" : 8 }, { "wk" : 3, "score" : 5 } ], "play" : [ { "wk" : 2, "score" : 8 }, { "wk" : 3, "score" : 5 } ] } 

I am trying to insert a new record into an array, if it is missing, and if the record is present in this array, then update this array record. Below is my MongoDB request.

 db.push.update( { _id: 5 }, { $push: { "quizzes": {"wk" : 6.0,"score" : 8.0},"play": {"wk" : 6.0,"score" : 8.0} } } ) 

Each time I execute this query, it inserts a new record into the array, but I want the record to be present, and then update this array.

+5
source share
1 answer

Use $addToSet instead of $push .

 db.push.update( { _id: 5 }, { $addToSet: { "quizzes": {"wk": 6.0, "score": 8.0}, "play": {"wk": 6.0, "score": 8.0} } } ) 

EDIT:

There is no simple built-in approach for updating a conditional subdocument in an array field for a specific property. However, a small trick can complete the task by completing two commands in a sequence.

For example: if we want to update the quizzes field using the { "wk": 7.0, "score": 8.0 } object, we can do this in two steps:

Step-1: $pull exit sub-documents from quizzes array, where "wk": 7.0 . (Nothing happens if the corresponding subdocument is not found).

 db.push.update( { _id: 5 }, { $pull: { "quizzes": { "wk": 7.0 } } } ) 

Step-2: $addToSet sub-document.

 db.push.update( { _id: 5 }, { $addToSet: { "quizzes": {"wk": 7.0, "score": 8.0} } } ) 

You can combine the two update commands above with bulk.find().update()

+8
source

Source: https://habr.com/ru/post/1263424/


All Articles