If I have a nested array in my schema, how do I tell MongoDB to remove its entries for a specific model?
Schema
var UserSchema = new Schema({
username: String,
documents: [Number]
});
I tried something like this:
db.users.update({"username": "tom"}, {"$pullAll": {"documents": []}})
But the items in the nested array are still there.
Extract particular element in MongoDB within a Nested Array? To extract the particular element in MongoDB, you can use $elemMatch operator. Let us first create a collection with documents −
To remove an element from a doubly-nested array in MongoDB document, you can use $pull operator. To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows − > db.removeElementFromDoublyNestedArrayDemo.insertOne( ... { ... "_id" : "1", ... "UserName" : "Larry", ...
You are calling method Pull (string name, MongoDB.Bson.BsonValue value) and according to the docs it Removes all values from the named array element that are equal to some value (see $pull) and you provide { "Identifier", productId } as the value. I guess that mongo does not find that exact value.
Usually when you make queries in MongoDB, the returned result is the whole document with all the fields unless you make a projection. However, sometimes you may want to filter some field, specifically an array field by a certain condition. There’re 3 options to achieve this: $elemMatch can be used in find operations.
Your code is not working, because $pullAll requires list of items which should be removed from array. You are passing empty array, thus nothing is removed.
You can simply set documents to empty array instead of removing all items:
db.users.update({"username": "tom"}, {"$set": {"documents": []}})
If you want to avoid creating documents array if "tom" do not have it, then check if array exists when selecting document to update:
db.users.update({username: "tom", documents: {$exists: true}},
{$set: {documents: []}})
UPDATE: Another option to remove all array items is to use $pull with query which satisfies all documents:
db.users.update({username: "tom"}, {$pull: {documents: {$exists: true}}})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With