根据数组元素查找对象,仅返回匹配的数组元素? [英] Find object based on array element, return only matching array element?
问题描述
我在猫鼬中有一个Person对象,并且该person对象具有多个对象(每个对象都有唯一的ID).
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'}]
}
然后查询:
Person.findOne({'things.id': 2},{'things.$': 1}, function(err, person) { ...
这很好用,但是我正在搜索所有Person对象(可能有很多).在这种情况下,我知道我需要的人的ID和事物"的一些唯一ID.通过id获取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;
}
});
我想知道的是,是否有更好的方法. IE.我可以通过id查询Person集合以仅得到一个Person,然后仅过滤出我要查找的内容(没有丑陋的循环)吗?
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)?
推荐答案
您可以在一个查询中同时包含两个id项,并且单个元素投影仍将起作用:
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) { ...
这篇关于根据数组元素查找对象,仅返回匹配的数组元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!