0

Mongodb条件操作符

Posted by 撒得一地 on 2016年3月29日 in Mongodb教程

描述

条件操作符用于比较两个表达式并从mongoDB集合中获取数据。

MongoDB中条件操作符有:

(>) 大于 - $gt
(<) 小于 - $lt
(>=) 大于等于 - $gte
(<= ) 小于等于 - $lte

<, <=, >, >= 这些操作符就不用多解释了,直接看用法,用法如下:

// 大于: field > value
db.collection.find({ "field" : { $gt: value } } ); 

// 小于: field < value
db.collection.find({ "field" : { $lt: value } } );

// 大于等于: field >= value 
db.collection.find({ "field" : { $gte: value } } );

// 小于等于: field <= valu
db.collection.find({ "field" : { $lte: value } } ); 

下面详细介绍实例,test数据库已经存在下面几条文档数据。

> db.test.find();
{"_id":ObjectId("4c220a42f3924d31102bd856"),"x":4,"j":1}
{"_id":ObjectId("4c220a42f3924d31102bd857"),"x":4,"j":2} 
{"_id":ObjectId("4c220a42f3924d31102bd858"),"x":4,"j":3 }

MongoDB (>) 大于操作符 – $gt

如果你想获取 "test" 集合中 "j" 大于 1 的数据,你可以使用以下命令:

>db.test.find({"j" : {$gt : 1}})
{"_id":ObjectId("4c220a42f3924d31102bd856"),"x":4,"j":1}
{"_id":ObjectId("4c220a42f3924d31102bd857"),"x":4,"j":2} 
{"_id":ObjectId("4c220a42f3924d31102bd858"),"x":4,"j":3}

类似于SQL语句:
Select * from test where j > 100;

MongoDB(>=)大于等于操作符 – $gte

如果你想获取"test"集合中 "j" 大于等于 2 的数据,你可以使用以下命令:

>db.test.find({"j" : {$gte : 2}})
{"_id":ObjectId("4c220a42f3924d31102bd857"),"x":4,"j":2} 
{"_id":ObjectId("4c220a42f3924d31102bd858"),"x":4,"j":3}

类似于SQL语句:
Select * from test where j >= 2;

MongoDB (<) 小于操作符 – $lt

如果你想获取"test"集合中 "j" 小于 2 的数据,你可以使用以下命令:

>db.test.find({"j" : {$lt : 2}})
{"_id":ObjectId("4c220a42f3924d31102bd856"),"x":4,"j":1}

类似于SQL语句:
Select * from test where j < 2;

MongoDB (<=) 小于操作符 – $lte

如果你想获取"test"集合中 "j" 小于等于 2 的数据,你可以使用以下命令:

>db.test.find({"j" : {$lte : 2}})
{"_id":ObjectId("4c220a42f3924d31102bd856"),"x":4,"j":1}
{"_id":ObjectId("4c220a42f3924d31102bd857"),"x":4,"j":2} 

类似于SQL语句:
Select * from test where j <= 2;

MongoDB 使用 (<) 和 (>) 查询 – $lt 和 $gt

如果你想获取"test"集合中 "j" 大于2,小于 4 的数据,你可以使用以下命令:

>db.test.find({"j" : {$lt :4, $gt : 2}})
{"_id":ObjectId("4c220a42f3924d31102bd858"),"x":4,"j":3}

类似于SQL语句:
Select * from test where j < 4 and j > 2;

MongoDB 使用 != 查询 – $ne

如果你想获取"test"集合中 "j" 不等于3 的数据,你可以使用以下命令:

>db.test.find({"j" : {$ne : 3}})
{"_id":ObjectId("4c220a42f3924d31102bd856"),"x":4,"j":1}
{"_id":ObjectId("4c220a42f3924d31102bd857"),"x":4,"j":2}

类似于SQL语句:
Select * from test where j < 3 or j > 3;

本文地址:http://coderschool.cn/1758.html

上一篇:

下一篇:

相关推荐

发表评论

电子邮件地址不会被公开。 必填项已用*标注

7 + 5 = ?

网站地图|XML地图

Copyright © 2015-2024 技术拉近你我! All rights reserved.
闽ICP备15015576号-1 版权所有©psz.