开发者

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

I am using MongoDB 1.8.1. I want to emulate Mongo’s $elemMatch query inside a $where clause, using the standard some method on JavaScript arrays. However, the query never matches anything, even if I provide a dummy function.

> 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 &开发者_开发问答amp;& this.bar.some(function() {return true;})'})
0

In the MongoDB shell itself, it works:

> [1, 2, 3].some(function() {return true;})
true

Why is this?


just add return before your where query it will work

> 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

But i prefer to use the function instead string in where claues, thats more clean

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜