如何在MongoDB中实现where条件过滤
其实,我们这些习惯传统关系型数据库开发的人,在过滤数据的时候可能首先想到的是where子句,所以MongoDB中也提供了“$where”。
示例:使用where进行数据查询
> db.emp.find({"$where":"this.age>40"}).pretty();
{
“_id” : ObjectId("599108423268c8e84253be2c"),
“姓名” : “郑琪”,
“性别” : “女”,
“年龄” : 50 ,
“sal” : 4700,
“loc” : “成都”
或者:
> db.emp.find("this.age>40" ).pretty();
{
"_id" : ObjectId("599108423268c8e84253be2c"),
"name" : "郑琪",
"sex" : "女" ,
"age" : 50,
"sal" : 4700,
"loc" : "成都"
}
"$where" 可以可以简化,但这种类型的操作贝尔ongs对每一行的信息进行判断。事实上,它不适合大量数据。使用不方便。其实上面的代码严格来说是一个写操作的函数。
> db.emp.find(function(){return this.age>40;}).pretty();< br/>{
"_id" : ObjectId("599108423268c8e84253be2c"),
"name" : "郑琪",
"sex" : "女",
"年龄" : 50,
"sal" : 4700,
"loc" : "成都"
}
> db.emp.find({"$where" :function(){return this.age>40;}}).pretty();
{
“_id” : ObjectId("599108423268c8e84253be2c"),
“name” : “郑Qi”,
“性别”:“女”,
“年龄”:50,
“sal”:4700,
“loc”:“成都”
}
上面只是一个查询,如果想实现多个条件的判断,那么就需要使用and连接。
> db.emp.find({"$and":[{"$where":"this.age>20"},{"$where":"this.age<25" }]}).pretty();
{
"_id" : ObjectId("599108423268c8e84253be27"),
"name" :"钱二",
"性别" : "女",
"年龄" : 22,
"sal" : 5000,
"loc" : "上海"
}
{
"_id" : ObjectId("599148bd0184ff511bf02b91"),
"姓名" : "林A",
"性别" : "男",
ot, " : [
"姓名": "林A的父亲",
uot; : 50,
"工作" : "农民"
},
br/> "年龄": 49 ,
"工作" : "工人"
br/> ]
}
2. 本站积分货币获取途径以及用途的解读,想在本站混的好,请务必认真阅读!
3. 本站强烈打击盗版/破解等有损他人权益和违法作为,请各位会员支持正版!
4. 编程技术 > 如何在MongoDB中实现where条件过滤