【问题标题】:Find object based on array element, return only matching array element?根据数组元素查找对象,只返回匹配的数组元素?
【发布时间】:2013-02-19 05:19:22
【问题描述】:

我在 mongoose 中有一个 Person 对象,而那个 person 对象有多个东西(每个东西都有一个唯一的 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 可能要快得多:

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

然后遍历所有东西以找到正确的:

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

我想知道是否有更好的方法。 IE。我可以通过 id 查询 Person 集合以仅获取一个 Person 然后过滤掉我正在寻找的东西(没有丑陋的循环)吗?

【问题讨论】:

  • things.$ 是什么意思? $ 指的是/做什么?
  • $ 是一个位置运算符。您可以在Mongo docs 中找到有关它的更多详细信息;)

标签: node.js mongodb mongoose


【解决方案1】:

您可以在单个查询中包含两个 id 术语,并且单个元素投影仍然有效:

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

【讨论】:

  • 那么这将首先查询 Person (应该很快),然后查询那个人的特定事物?太棒了,谢谢!
  • 那么这是否意味着 person 对象将只返回 things 数组中的一个元素,即我们在查询中要查找的东西?
  • 不错。我现在正在寻找一种方法来做到这一点,但使用 findOneAndUpdate,因为我只需要更新文档数组的特定元素。您对如何实现这一点有任何想法吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-23
  • 2012-10-25
  • 1970-01-01
  • 2018-05-17
  • 1970-01-01
  • 2016-07-25
相关资源
最近更新 更多