1

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!

0

1 Answer 1

2

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" } ] }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! Both ways have worked for me, I would prefer direct $pull for one lesser operation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.