本文介绍了MongoDB,从数组中删除对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
文档:
{
_id: 5150a1199fac0e6910000002,
name: 'some name',
items: [{
id: 23,
name: 'item name 23'
},{
id: 24,
name: 'item name 24'
}]
}
有没有办法从数组中提取特定对象?IE.如何从 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 将从数组中提取一个字段,而不是一个对象.
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.
推荐答案
try..
db.mycollection.update(
{ '_id': ObjectId("5150a1199fac0e6910000002") },
{ $pull: { items: { id: 23 } } },
false, // Upsert
true, // Multi
);
这篇关于MongoDB,从数组中删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!