Search code examples
javascriptnode.jsmongodbunset

Mongodb $unset leaves empty array object(javascript)


I am using mongo "$unset" command to remove all matching documents for a certain criteria where index is not known.

Let's say collection looks like:-

{
    "_id" : 1,
    "list" : [
        {
            "key" : "a"
        },
        {
            "key" : "b"
        },
        {
            "key" : "c"
        }
    ]
}

Mongo shell command used to unset keys matching "b":-

db.test.update({"list.key":"b"}, {$unset: {'list.$.key':"b"}})

Result:-

{
    "_id" : 1,
    "list" : [ {"key" : "a"}, {}, {"key" : "c"} ]
}

Answer needed for:- How to remove the empty array object?

Note:- I have read pages suggesting to use $pull:null, but that doesn't fit in here.

Thanks!


Solution

  • If you really want to unset it first and then pull the element(s) missing key off the array use:

    db.test.update(
      { "_id": 1 },  // you can also use { } to clean up the whole collection
      { $pull: { "list": { "key": {$exists: false} } } }
    )
    

    But if there is not strong reason for this use pull to do it in one shot:

    db.test.insert({ 
      "_id" : 1, 
      "list" : [ { "key": "a" }, { "key": "b" }, { "key": "c" } ] 
    })
    

    You can use pull to remove from the document where list contains a key with value b:

    db.test.update({ 
      "list.key": "b" }, 
      { $pull: { "list": {"key": "b" } } 
    })
    

    This removes the respective element from the array:

    db.test.find()
    { "_id" : 1, "list" : [ { "key" : "a" }, { "key" : "c" } ] }