$where ,其实就是 mongo中执行 js代码,来完成查询,直接执行脚本语言是很危险的事情,谨记谨记
不是非常必要的话 不推荐使用 $where
1、mongo要先把数据从 bson转为js对象
2、$where 不使用索引
但不管怎么说,先达到目的吧
比如 查询 2个值相等
先find 确认一下数据库当前的数据
> db.ttt.find({})
{ "_id" : 1, "a" : 1, "b" : 1, "c" : 3 }
{ "_id" : 2, "a" : 2, "b" : 1, "c" : 3 }
> db.ttt.find({$where:"this.a == this.b"})
{ "_id" : 1, "a" : 1, "b" : 1, "c" : 3 }
function a(){if( this.a == this.b){return true;}return false;
}
> db.ttt.insert({"_id":3,"a":{"b":1,"c":2,"d":1}})
WriteResult({ "nInserted" : 1 })
> db.ttt.find({})
{ "_id" : 1, "a" : 1, "b" : 1, "c" : 3 }
{ "_id" : 2, "a" : 2, "b" : 1, "c" : 3 }
{ "_id" : 3, "a" : { "b" : 1, "c" : 2, "d" : 1 } }
如果直接用
function a(){if(this.a.b == this.a.d){return true;}return false;
}
> db.ttt.find({$where:"function a(){if(this.a.b == this.a.d){return true;}return false;}"})
{ "_id" : 1, "a" : 1, "b" : 1, "c" : 3 }
{ "_id" : 2, "a" : 2, "b" : 1, "c" : 3 }
{ "_id" : 3, "a" : { "b" : 1, "c" : 2, "d" : 1 } }
则不能得到想要的结果,需要其他数据没有的值进行判空
function a(){var x = this.a.b;var y = this.a.d;if( x == null)return falseif( y == null)return falseif(x == y){return true;}return false;
}
> db.ttt.find({$where:"function a(){var x = this.a.b;var y = this.a.d;if( x == null){return false;}if( y == null){return false;}if(x == y){return true;}return false;}"})
{ "_id" : 3, "a" : { "b" : 1, "c" : 2, "d" : 1 } }