MongoDB, remove object from array
100,268
Solution 1
try..
db.mycollection.update(
{ '_id': ObjectId("5150a1199fac0e6910000002") },
{ $pull: { items: { id: 23 } } },
false, // Upsert
true, // Multi
);
Solution 2
I have a document like
I have to delete address from address array
After searching lots on internet I found the solution
Customer.findOneAndUpdate(query, { $pull: {address: addressId} }, (err, data) => {
if (err) {
return res.status(500).json({ error: 'error in deleting address' });
}
res.json(data);
});
Solution 3
my database:
{
"_id" : ObjectId("5806056dce046557874d3ab18"),
"data" : [
{ "id" : 1 },
{ "id" : 2 },
{ "id" : 3 }
]
}
my query:
db.getCollection('play_table').update({},{$pull:{"data":{"id":3}}},{multi:true}
output:
{
"_id" : ObjectId("5806056dce046557874d3ab18"),
"data" : [
{ "id" : 1 },
{ "id" : 2 }
]
}
Solution 4
You can try it also:
db.getCollection('docs').update({ },{'$pull':{ 'items':{'id': 3 }}},{multi:true})
Solution 5
For a single record in array:
db.getCollection('documents').update(
{ },
{'$pull':{ 'items':{'mobile': 1234567890 }}},
{new:true}
);
For a multiple records with same mobile number in array:
db.getCollection('documents').update(
{ },
{
$pull: {
items: { mobile: 1234567890 }
}
},
{ new:true, multi:true }
)
Related videos on Youtube
Author by
lostintranslation
Updated on June 20, 2021Comments
-
lostintranslation almost 3 years
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.
-
Myrne Stol about 11 yearsHave you tried this? stackoverflow.com/questions/9048424/…
-
lostintranslation about 11 yearsyup that is it. Thanks!
-
-
lostintranslation about 11 yearsyup, my syntax was wrong. Thanks! Also tried without the upset and multi options and that worked as well.
-
Nicolas Del Valle almost 7 yearsWhat are those boolean values?
-
Lukas Liesis about 6 years@NicolasDelValle if I remember correctly, these were options
upsert
andmulti
. For current syntax & documentation check this link: docs.mongodb.com/manual/reference/method/db.collection.update -
Ever Think about 4 yearsHow to do this in MongoDB CLI ?
-
Vikas Chauhan about 3 yearsI think this is nodejs (express) solution not the MongoDB query solution