为什么Array不.有些工作在Mongo的$where子句中
Why doesn’t Array.some work in Mongo’s $where clause?
我使用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
相关文章:
- 在查询字符串中查找 where 子句
- 将where子句与javascript变量一起使用
- 使环回模型得到“;存在”;带有where子句的方法
- 如何在 alasql 中的 where 子句中放置特定日期
- 用于检索所有用户的 where 子句
- DexieJS(indexedDB)链多个.where子句
- 执行带有 WHERE 子句的 Sql 在 Phonegap 中不返回任何结果
- 筛选 Azure 移动服务节点.js上的 where 子句的功能
- Google 地图 API v3 中的 where 子句
- Sails.js:在查询模型时,将查询列指定为where子句中的变量
- Javascript SQL请求where子句中出现错误字段错误
- 带有where子句的Insert语句不会在nodejs-mysql上运行
- 如何在 where 子句中使用动态查询字段
- 谷歌地图融合层忽略WHERE子句
- sequelize-带有关联的Where子句
- 在sails.js中关联模型的Where子句
- 用NOT LIKE where子句序列化查询
- SQLite:当前日期加上where子句中的一天
- Where子句在' OR '语句中使用包含关系
- 为什么Array不.有些工作在Mongo的$where子句中