user3210973
user3210973

Reputation: 60

Query mongo document based on its subdocument using $exists

I am trying to fetch records from mongo using mongoose. I have document called projects that has sub-document work. work has user, to and from properties. I want to fetch the document that has specific user, and doesn't have to value set.

So far i tried:

models.project.findOne {'work.user': user,'work.to':{$exists: false}},
  (err, data) -> # data is always null, no error.

It seems that if just one of objects in work contains property 'to' then $exists: equals to true. Is there a way to do this?

Also here is same code in JS if you prefer:

models.project.findOne({
  'work.user': user,
  'work.to': {
    $exists: false
  }
}, function(err, data) {});

Thanks for your time.

Upvotes: 0

Views: 86

Answers (2)

anhlc
anhlc

Reputation: 14479

You can use $elemMatch in this case, which will return results only when specific user matched and doesn't have to value set in the same array element:

models.project.users.findOne({
"work" : { $elemMatch: {"user":user, "to": {$exists: false}}}
}, function(err, data) {});

Upvotes: 2

harryy000
harryy000

Reputation: 553

you could use "null" for this case instead of $exists

models.project.findOne({
  'work.user': user,
  'work.to': null
}, function(err, data) {});

Upvotes: 1

Related Questions