0

I am extremely new to mongodb and am facing a little trouble with an update operation. Here is the document:

{
    "username" : "amitverma",
    "notifications" : {
        "notification_add_friend" : [
            {
                "sender" : "macbook",
                "action" : "",
                "type" : "",
                "objectType" : "request",
                "objectUrl" : "",
                "isUnread" : true
            },
            {
                "sender" : "safari",
                "action" : "",
                "type" : "",
                "objectType" : "request",
                "objectUrl" : "",
                "isUnread" : true
            },
            {
                "sender" : "chrome",
                "action" : "",
                "type" : "",
                "objectType" : "request",
                "objectUrl" : "",
                "isUnread" : true
            }
        ]
    },
    "_id" : ObjectId("526598c86f45240000000001")
}
{
    "username" : "macbook",
    "notifications" : {
        "notification_add_friend" : [
            {
                "sender" : "amitverma",
                "action" : "",
                "type" : "",
                "objectType" : "a_r",
                "objectUrl" : "",
                "isUnread" : true
            }
        ]
    },
    "_id" : ObjectId("526598d06f45240000000002")
}

I want to remove the sub array with {"sender":"safari"} within "username":"amitverma" I have tried $elemMatch with $set, but just couldn't get the query correctly.

4

1 回答 1

3

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
  }
})
于 2013-10-21T22:03:06.050 回答