MongoDB的$where查询

来源:互联网 发布:vscode新建c工程 编辑:程序博客网 时间:2024/06/05 12:47

有时候,键值对的查询方式并不能满足我们的需求,我们有如下一个集合:

> db.foo.find()
{ “_id” : ObjectId(“4e9165cf717ed94f8289ac0c”), “bar” : “baz”, “count” : 35 }
{ “_id” : ObjectId(“4e916661739f1da5452a4dfe”), “bar” : “bazz”, “count” : 3 }
{ “_id” : ObjectId(“4e9165cf717ed94f8289ac0d”), “bar” : “baz”, “count” : 35 }
{ “_id” : ObjectId(“4e928bf8735a86e2c6f848ed”), “apple” : 1, “banana” : 6, “peach” : 3 }
{ “_id” : ObjectId(“4e928c17735a86e2c6f848ee”), “apple” : 1, “spinach” : 4, “watermelon” : 4 }
{ “_id” : ObjectId(“4e928d8a735a86e2c6f848ef”), “bar” : “baz”, “banana” : “baz” }

需要返回有两个字段相同的文档,也就是要返回如下文档

{ “_id” : ObjectId(“4e928c17735a86e2c6f848ee”), “apple” : 1, “spinach” : 4, “watermelon” : 4 }
{ “_id” : ObjectId(“4e928d8a735a86e2c6f848ef”), “bar” : “baz”, “banana” : “baz” }

就需要使用”$where“并借助javascript来做了

db.pa_yunju_logistics.find({"$where":
 "this.erp_code!=this.code"
})

 或者

db.pa_yunju_logistics.find({"$where":function(){
 return this.erp_code!=this.code
}
})

> db.foo.find({“$where”:function(){
… for(var current in this){
…   for(var other in this){
…     if(current != other && this[current] == this[other]){
…       return true;
…     }
…   }
… }
… return false;
… }})

如果返回true,文档作为结果的一部分被返回;如果为false,则不会返回。

$where查询有以下几种写法:

> db.foo.find({“$where”:”this.x+this.y==10″})
> db.foo.find({“$where”:”function(){return this.x+this.y==10;}”})

tips:不是非常必要时,一定要避免使用”$where”查询,因为效率太低,相当的。文档在MongoDB中是以BSON格式保存的,在$where查询时,每个文档都要从BSON转换为javascript对象然后再通过”$where”中的表达式来运行。有时可以将常规查询作为前置过滤,再使用”$where”查询对结果进行调优

0 0
原创粉丝点击