Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find object based on array element, return only matching array element?

I have a Person object in mongoose, and that person object has multiple things (each thing has a unique ID).

person1 = {
  things[{id: 1, name: 'one'},{id:2, name: 'two'}]
}
person2 = {
  things[{id: 3, name: 'three'},{id:4, name: 'four'}]
}

then query:

Person.findOne({'things.id': 2},{'things.$': 1}, function(err, person) { ...

This works great but I am searching through all Person objects (which there could be a lot of). In this case I know the id of the Person I need and some unique id of a 'thing'. Its probably a lot faster to get the Person by id:

Person.findById(personId, function(err, person) { ...

Then loop over all the things to find the right one:

var thing
person.things.forEach(function(t) {
  if (t.id == thingId) {
    thing = t;
  }
});

What I am wondering is if there is a better way. I.E. can I query the Person collection by id to get just one Person then filter out just the thing I am looking for (without the ugly loop)?

like image 348
lostintranslation Avatar asked Mar 04 '13 23:03

lostintranslation


1 Answers

You can include both id terms in a single query and the single element projection will still work:

Person.findOne({_id: personId, 'things.id': 2}, {'things.$': 1}, 
    function(err, person) { ...
like image 162
JohnnyHK Avatar answered Sep 28 '22 07:09

JohnnyHK