Update element in array if exists else insert new element in that array in MongoDb

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 conditional sub-document update in an array field, by specific property. However, a small trick can do the job by executing two commands in sequence.

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

Step-1: $pull out sub-documents from the quizzes array where "wk": 7.0. (Nothing happens if matching sub-document not found).

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

Step-2: $addToSet the sub-document.

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

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

Tags:

Arrays

Mongodb