0

I have added undefined values to array using script performed on a server side (Mongo version - 3.4.10).

Let's say I have document like

{
   "array" : ["a","b", undefined]
}

and I want to remove undefined element.

When I query it like this

find({"array" :  {$elemMatch : {$in : [null], $exists : true} }})

It returns above document - Mongo treats null and undefined as equal.

However, below update query is not removing element as expected (works fine for nulls)

update({} ,{ $pull : {"array" : {$in : [null]} }}, {multi : true})

It is also not possible to use undefined as math expression

InMatchExpression equality cannot be undefined

Question: How do you remove elements in such a situation?

2
  • 3
    Have you tried db.collection.updateMany({}, {"$pull": { "array": undefined }});? Commented Mar 23, 2018 at 11:48
  • @kadiii Added my answer below, check it out.. Commented Mar 24, 2018 at 4:15

1 Answer 1

4
db.collection.update(
 {},
 {$pull: {"address.coord":{$type: 6}}},
 {multi:true}

)

Refer the type & pull operators for more details. It will remove all the undefined matches as per your requirement. If your document structure have nested arrays, use $[] positional operators.

Sign up to request clarification or add additional context in comments.

Comments

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.