我使用的是 MongoDB 1.8.1。我想在 $where
子句中模拟 Mongo 的 $elemMatch
查询,使用 JavaScript 数组上的标准 some
方法。但是,即使我提供了虚拟函数,查询也不会匹配任何内容。
> db.foo.insert({bar: [1, 2, 3]})
> db.foo.count({$where: 'this.bar && (this.bar.length > 0)'})
1
> db.foo.count({$where: 'this.bar && this.bar.some'})
1
> db.foo.count({$where: 'this.bar && this.bar.some(function() {return true;})'})
0
在 MongoDB shell 本身中,它可以工作:
> [1, 2, 3].some(function() {return true;})
true
这是为什么?
最佳答案
只需在 where 查询之前添加 return 即可工作
> db.foo.count({$where: 'return this.bar && this.bar.some(function() {return true;})'})
> 1
> db.foo.count({$where: 'return this.bar && this.bar.some(function(bar) {return bar>2;})'})
> 1
> db.foo.count({$where: 'return this.bar.some(function(bar) {return bar==1;}) && this.bar.some(function(bar) {return bar==6;})'})
> 0
但我更喜欢在 where claues 中使用函数而不是字符串,这样更干净
>db.foo.count({$where: function() { return this.bar.some(function(bar) { return bar > 1;}) & this.bar.some(function(bar) { return bar > 2;}) }})
>1
关于javascript - 为什么 Array.some 在 Mongo 的 $where 子句中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7415917/