开发者

MongoDb remove subdocument from document

I have a collection with a following data:

{

  "_id" : ObjectId("4e3951905e746b3805000000"),
  "m" : "hello",
  "r" : [{
      "_id" : ObjectId("4e3951965e746b8007000000"),
      "u" : 3,
      "m" : "response1"
    }, {
      "_id" : ObjectId("4e39519d5e746bc00f000000"),
      "u" : 3,
      "m" : "response2"
    }, {
      "_id" : ObjectId("4e3953dc5e746b5c07000000"),
      "u" : 3,
      "m" : "response3"
    }, {
      "_id" : ObjectId("4e3953ea5e746bd40f000001"),
      "u" : 3,
      "m" : "response"
    }],
  "u" : 3,
  "w" : 3
}
{
  "_id" : ObjectId("4e3952c75e746bd807000001"),
  "m" : "asdfa",
  "r" : [{
      "_id" : ObjectId("4e395开发者_开发技巧44e5e746bc00f000001"),
      "u" : 3,
      "m" : "response5"
    }],
  "u" : 3,
  "w" : 3
}

Can anyone suggest how to remove a subdocument from a 'r' key having only id of subdocument, I am going to del?

for instance i want to del a subdocument with id 4e39519d5e746bc00f000000 So this subdocument should be deleted

{
  "_id" : ObjectId("4e39519d5e746bc00f000000"),
  "u" : 3,
  "m" : "response2"
},


It's easy, you just need to use $pull operator:

db.items.update( {}, 
{ $pull : { r : {"_id": ObjectId("4e39519d5e746bc00f000000")} } }, false, false )


dbh.users.update({"_id": ObjectId("4e39519d5e746bc00f000000")}, {"$unset":{"r":1}},False,False)

Try using unset

Reference: MongoDB : Update Modifier semantics of "$unset"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜