Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB - Clearing items in a nested array

Tags:

mongodb

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.

like image 286
Evan Emolo Avatar asked Aug 08 '13 22:08

Evan Emolo


People also ask

How to extract particular element in MongoDB within a nested array?

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 −

How to remove element from a doubly-nested array in MongoDB document?

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", ...

How to remove all values from a named array in MongoDB?

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.

How do I filter an array field in MongoDB?

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.


1 Answers

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}}})
like image 189
Sergey Berezovskiy Avatar answered Oct 07 '22 00:10

Sergey Berezovskiy