MongoDB,从数组中删除对象

127

文件:

{
   _id: 5150a1199fac0e6910000002,
   name: 'some name',
   items: [{
      id: 23,
      name: 'item name 23'
   },{
      id: 24,
      name: 'item name 24'
   }]
}

有没有办法从数组中提取特定的对象?比如说,我要如何从items数组中提取id为23的整个item对象。

我尝试过:

db.mycollection.update({'_id': ObjectId("5150a1199fac0e6910000002")}, {$pull: {id: 23}});

然而我很确定我没有正确使用“pull”。据我所知,pull将从数组中拉出一个字段,但不包括对象。

有任何想法如何从数组中提取整个对象。

作为奖励,我正在尝试在mongoose/nodejs中实现这一点,但我不确定mongoose API中是否有此类功能,因为我找不到它。


1
你尝试过这个吗?https://dev59.com/0Wox5IYBdhLWcg3wq2EC - Myrne Stol
8个回答

210

尝试..

db.mycollection.update(
    { '_id': ObjectId("5150a1199fac0e6910000002") }, 
    { $pull: { items: { id: 23 } } },
    false, // Upsert
    true, // Multi
);

是的,我的语法错了。谢谢!我也尝试了不带烦恼和多选项的方式,也行。 - lostintranslation
15
这些布尔值是什么? - Nicolas Del Valle
2
如果我没记错的话,这些选项是 upsertmulti。有关当前语法和文档,请查看此链接:https://docs.mongodb.com/manual/reference/method/db.collection.update/。 - Lukas Liesis

13

我有一个像这样的文档

enter image description here

我必须从地址数组中删除地址

在互联网上搜了很多后,我找到了解决方案

Customer.findOneAndUpdate(query, { $pull: {address: addressId} }, (err, data) => {
    if (err) {
        return res.status(500).json({ error: 'error in deleting address' });
    }

    res.json(data);
});

如何在MongoDB CLI中执行此操作? - Ever Think
1
我认为这是Node.js(Express)的解决方案,而不是MongoDB查询解决方案。 - Vikas Chauhan

8

我的数据库:

{
  "_id" : ObjectId("5806056dce046557874d3ab18"),
  "data" : [ 
    { "id" : 1 }, 
    { "id" : 2 }, 
    { "id" : 3 }
  ]
}
    

我的查询:

db.getCollection('play_table').update({},{$pull:{"data":{"id":3}}},{multi:true}

输出:

{
  "_id" : ObjectId("5806056dce046557874d3ab18"),
  "data" : [ 
    { "id" : 1 }, 
    { "id" : 2 }
  ]
}

6
你也可以尝试一下:
db.getCollection('docs').update({ },{'$pull':{ 'items':{'id': 3 }}},{multi:true})

6

针对数组中的单个记录:

db.getCollection('documents').update(
    { },
    {'$pull':{ 'items':{'mobile': 1234567890 }}},
    {new:true}
);

针对一个具有相同手机号的多个记录数组:

db.getCollection('documents').update(
    { },
    {
        $pull: {
            items: { mobile: 1234567890 }
        }
    },
    { new:true, multi:true }
)

1
使用$pull来删除数据。
return this.mobiledashboardModel
.update({"_id": args.dashboardId}, { $pull: {"viewData": { "_id": widgetId}}})
.exec()
.then(dashboardDoc => {
     return {
        result: dashboardDoc
     }
});

0
Very simple way to do this:-

Sample data that I used is:-
{
            "_id": "6419606109433f61b50dfaa4",
            "category": "SUV",
            "vehicles": [
                {
                    "id": "18d527aa-948e-40bc-9ce1-c54dc04a6350"
                    "name": "Honda City 4th Generation",
                    "average": "23.26 kmpl",
                    "cc": "1197 cc",
                    "seat": "5 Seater",
                },
{
                    "id": "18d527aa-948e-40bc-9ce1-c54dc04a6349"
                    "name": "Honda City 4th Generation",
                    "average": "23.26 kmpl",
                    "cc": "1197 cc",
                    "seat": "5 Seater",
                },
}

exports.delete_vehicle = async (req, res, next) => {
  const { id, vuuid } = req.params;
  const vehicle = await VehicleCategory.find({ _id: id });
  try{
    for(let i = 0; i < vehicle[0].vehicles.length; i++){
      if(vehicle[0].vehicles[i].id === vuuid){
        await VehicleCategory.findByIdAndUpdate(
          {_id:id},
          { $pull: { vehicles: { id: vuuid } } },
          { new: true }
        );
        res.status(200).json({
          message: "Vehicle deleted successfully."
        });
      }else{
        res.status(404).json({
          message: "The given id is not found."
        });
      }
    }
  }catch (err) {
    res.status(500).json({
      error: err
    });
  }
  

};

router.put("/deleteVehicle/:id/:vuuid", userController.delete_vehicle);

路由器.放置("/删除车辆/:id/:vuuid", 用户控制器.删除车辆);


0

基绍尔·迪亚纳:

如果您想删除所有元素,包括元素属性列表的键。

以下是mongoDB unset运算符的示例:

db.UM_PREAUTH_CASE.update(
{ 'Id' : 123}, { $unset: { dataElements: ""} } )

JSON 的样子看起来像这样:

{ "Id":123,"dataElements" : [ { "createdBy" : "Kishore Babu Diyyana", "createdByUserId" : 2020 }, { "createdBy" : "Diyyana Kishore", "createdByUserId" : 2021 } ] }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接