0

我可以用 MongoDB 查询做这样的事情吗(我也在使用 MongooseJS)。

在 lodash 中,我可以这样

var characters = [
  { 'name': 'barney',  'age': 36, 'blocked': false },
  { 'name': 'fred',    'age': 40, 'blocked': true },
  { 'name': 'pebbles', 'age': 1,  'blocked': false }
];

_.find(characters, function(chr) {
  // Do any kind of logic and ultimately return a boolean.
  return chr.age - 10 > 24;
}); // returns barney and fred

我可以用内置的 mongo 驱动程序或 mongoosejs 做这样的事情吗?我宁愿不读取所有对象并像这样遍历它们,因为它们可能很多。我宁愿 mongo 为我做这件事。

谢谢!

4

2 回答 2

1

虽然出于性能原因不建议这样做(因为它必须遍历每个文档并执行 JavaScript 而不能使用索引),但您可以使用$where运算符 ( reference ) 来执行自定义 JavaScript 代码:

db.theCollection.find({ $where : "this.age - 10 > 24" })

(而且我猜真正的逻辑会更复杂,因为可以不使用$where:来处理该查询find({age: { $gt : 24 }})。如果可能,请尝试使用内置的查询运算符,因为它们通常更有效,并且通常更容易使用字段索引。

于 2013-12-01T16:32:39.187 回答
-1

Lo-Dash 遍历元素并将每个元素传递给回调。看起来做起来并不容易。它需要创建一些非常复杂的东西,能够识别回调函数中的条件(解析它),然后尝试使用索引并在它们的帮助下过滤记录。

MongoDB 没有这样的选项。

于 2013-12-01T10:36:25.223 回答