MongoDB - Clearing items in a nested array

19,984

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}}})
Share:
19,984

Related videos on Youtube

Evan Emolo
Author by

Evan Emolo

Updated on June 04, 2022

Comments

  • Evan Emolo
    Evan Emolo over 1 year

    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.