David Paniz
David Paniz

Reputation: 21

Mongodb: find embedded element missing some key

I have a document with an embedded collection, but few elements are missing a key and I have to find all those elements. Here is an example:

var foo = {name: 'foo', embedded: [{myKey: "1", value: 3}, {myKey: "2", value: 3}]}
db.example.insert(foo)
var bar = {name: 'bar', embedded: [{value: 4}, {myKey: "3", value: 1}]}
db.example.insert(bar)

I need a query that returns the 'bar' object because one of its embedded doesn't have the key 'myKey'.

I try to use the $exists, but it returns only if ALL embedded elements are missing the key

db.example.find({'embedded.myKey': {$exists: true}}).size()
// -> 2
db.example.find({'embedded.myKey': {$exists: false}}).size()
// -> 0

How can I find the documents that at least one embedded element is missing the key 'myKey'?

Upvotes: 2

Views: 996

Answers (1)

Abhishek Kumar
Abhishek Kumar

Reputation: 3366

If 'value' is always present, then you can try this command

db.example.find({ embedded : { $elemMatch : { value : {$exists : true},  myKey : {$exists : false}}  }})
{ "_id" : ObjectId("518bbccbc9e49428608691b0"), "name" : "bar", "embedded" : [ { "value" : 4 }, { "myKey" : "3", "value" : 1 } ] }

Upvotes: 3

Related Questions