如何从MongoDB中的数组对象中删除特定对象

时间:2013-12-05 07:45:30

标签: mongodb

mycode如下所示: -

{
  "_id" : ObjectId("52a02251305157fe20ce140f"),
  "cats" : [
          {
                  "catname" : "elect",
                  "disname" : "Elect",
                  "subcats" : [
                          {
                                  "subcatname" : "mobile",
                                  "subdisname" : "Mobiles"
                          },
                          {
                                  "subcatname" : "cam",
                                  "subdisname" : "Cam"
                          }
                  ]
          }
  ]
  } 

我想删除子设备中的移动设备,我尝试如下: -

 db.demo.update({"cats.catname":"elect"},{$pull: {"subcats.$.subcatname":"mobile"}},  {"upsert":true})

删除移动代码后如下所示(我预期如下): -

 {
  "_id" : ObjectId("52a02251305157fe20ce140f"),
  "cats" : [
          {
                  "catname" : "elect",
                  "disname" : "Elect",
                  "subcats" : [
                          {
                                  "subcatname" : "cam",
                                  "subdisname" : "Cam"
                          }
                  ]
          }
    ]
    } 

最诚挚的问候 GSY

2 个答案:

答案 0 :(得分:1)

您可以使用 $ pull 运算符将其删除。查询应如下:

db.myObject.update(
    {"cats.catname" : "elect"},
    {$pull:{"cats.$.subcats" : {subcatname : "mobile"}}}
);

答案 1 :(得分:0)

{$pull: {"subcats.$.subcatname":"mobile"}}

但是

{$pull: {"cats.$.subcats":{"subcatname":"mobile"}}

>

db.demo.update({"cats.catname":"elect"},{$pull: {"cats.$.subcats":{"subcatname":"mobile"}}})