2013-10-21 135 views
0

我对mongodb非常陌生,在更新操作中遇到了一些麻烦。下面是文档:Mongodb在子阵列内更新操作

{ 
    "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") 
} 

我想与{"sender":"safari"}"username":"amitverma" 我曾尝试$ elemMatch与$集删除子阵列,但就是无法得到正确的查询。

+0

如果我正确理解你,你想从第一个文档中删除整个'notification_add_friend'数组? * P.S。其实这里有两个文件* – Shad

+0

我*认为* OP意味着从阵列中删除“safari”请求,但措辞有点奇怪。如果打算删除整个数组,我将删除/更改我的答案。 – numbers1311407

回答

2

你不想在这里使用$set,但$pullsee docs),而你使用$elemMatch进一步指定查询,你不需要。

下会拉所有{"sender": "safari"}从文档的子阵列匹配{"username": "amitverma"}

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

至于您的评论添加好友通知,如果您想更新您的特定元素使用$set组合与$elemMatchpositional operator $。对于你的例子,如:

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

如果我想改变一个特定的属性,比如'isUnread'为false,那我该怎么做? – amit

+0

用于更改isUnread值的更新解决方案不起作用。 – amit

+0

它应该工作,你得到一个错误,或者它只是没有更新?你在用什么版本的mongo? – numbers1311407