MongoDB,从数组中删除对象 [英] MongoDB, remove object from array

查看:520
本文介绍了MongoDB,从数组中删除对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Doc:

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

有没有办法拉出特定的对象从阵列? I.E.如何从items数组中提取id为23的整个item对象。

Is there a way to pull a specific object from an array? I.E. how do I pull the entire item object with id 23 from the items array.

我试过:

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

但我很确定我没有正确使用'pull'。根据我的理解,pull将从数组中提取字段而不是对象。

However I am pretty sure that I am not using 'pull' correctly. From what I understand pull will pull a field from an array but not an object.

任何想法如何将整个对象拉出数组。

Any ideas how to pull the entire object out of the array.

作为奖励,我试图在mongoose / nodejs中执行此操作,并且不确定这种类型的东西是否在mongoose API中但是我找不到它。

As a bonus I am trying to do this in mongoose/nodejs, as well not sure if this type of thing is in the mongoose API but I could not find it.

推荐答案

试试..

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

这篇关于MongoDB,从数组中删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆