为什么Array不.有些工作在Mongo的$where子句中

Why doesn’t Array.some work in Mongo’s $where clause?

本文关键字:where 子句 Mongo Array 工作 为什么      更新时间:2023-09-26

我使用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子句中使用函数而不是字符串,这样更干净

>db.foo.count({$where: function() { return  this.bar.some(function(bar) { return bar > 1;}) & this.bar.some(function(bar) { return bar > 2;}) }})
 >1