Skip to content Skip to sidebar Skip to footer

Mongodb Update Operation Inside Sub Array

I am extremely new to mongodb and am facing a little trouble with an update operation. Here is the document: { 'username' : 'amitverma', 'notifications' : { 'notif

Solution 1:

You don't want to use $set here, but $pull (see docs), and while you could use $elemMatch to further specify your query, you do not need to.

The following would pull all add friend notifications with {"sender": "safari"} from the sub array of documents matching {"username": "amitverma"}

db.yourcollection.update({"username": "amitverma"}, { 
  $pull: {"notifications.notifications_add_friend": {"sender": "safari"}}
})

As to your comment, if you wanted to update a particular element you would use $set in combination with $elemMatch and the positional operator $. For your example, something like:

db.yourcollection.update({
  "username": "amitverma", 
  "notifications.notifications_add_friend": {
    $elemMatch: {"sender": "safari"}
  }
}, {
  $set: {
    "notifications.notifications_add_friend.$.isUnread": false
  }
})

Post a Comment for "Mongodb Update Operation Inside Sub Array"