MongoDB, remove object from array

Doc:

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

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.

I have tried:

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

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.

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.

112247 次浏览

试试。

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

我有一份文件

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);
});

我的数据库:

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

我的问题是:

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

output:

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

使用 $pull删除数据

return this.mobiledashboardModel
.update({"_id": args.dashboardId}, { $pull: {"viewData": { "_id": widgetId}}})
.exec()
.then(dashboardDoc => {
return {
result: dashboardDoc
}
});

你也可以试试:

db.getCollection('docs').update({ },{'$pull':{ 'items':{'id': 3 }}},{multi:true})

对于数组中的单个记录:

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

对于数组中具有相同移动号码的多个记录:

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

迪亚纳:

If you want to remove all elements including the key of the element attributes list.

下面是 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 } ] }