前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >mongodb查询的语法总结

mongodb查询的语法总结

作者头像
周小董
发布2019-03-25 14:28:46
1.5K0
发布2019-03-25 14:28:46
举报
文章被收录于专栏:python前行者python前行者
  1. 大于,小于,大于或等于,小于或等于

$gt:大于 $lt:小于 $gte:大于或等于 $lte:小于或等于

例子:

代码语言:javascript
复制
db.collection.find({ "field" : { $gt: value } } ); // greater than : field > value
db.collection.find({ "field" : { $lt: value } } ); // less than : field < value
db.collection.find({ "field" : { $gte: value } } ); // greater than or equal to : field >= value
db.collection.find({ "field" : { $lte: value } } ); // less than or equal to : field <= value

如查询j大于3,小于4:

代码语言:javascript
复制
db.things.find({j : {$lt: 3}});
db.things.find({j : {$gte: 4}});
也可以合并在一条语句内:
db.collection.find({ "field" : { $gt: value1, $lt: value2 } } ); // value1 < field < value
  1. 不等于 $ne

例子:

代码语言:javascript
复制
db.things.find( { x : { $ne : 3 } } );
  1. in 和 not in ($in $nin)

语法:

代码语言:javascript
复制
db.collection.find( { "field" : { $in : array } } );

例子:

代码语言:javascript
复制
db.things.find({j:{$in: [2,4,6]}});
db.things.find({j:{$nin: [2,4,6]}});
  1. 取模运算$mod

如下面的运算:

代码语言:javascript
复制
db.things.find( "this.a % 10 == 1")
可用$mod代替:
db.things.find( { a : { $mod : [ 10 , 1 ] } } )
  1. $all

all和all和all和in类似,但是他需要匹配条件内所有的值:

如有一个对象:{ a: [ 1, 2, 3 ] } 下面这个条件是可以匹配的:

代码语言:javascript
复制
db.things.find( { a: { $all: [ 2, 3 ] } } );

但是下面这个条件就不行了:

代码语言:javascript
复制
db.things.find( { a: { $all: [ 2, 3, 4 ] } } );
  1. $size

$size是匹配数组内的元素数量的,如有一个对象:{a:[“foo”]},他只有一个元素:

下面的语句就可以匹配:db.things.find( { a : { $size: 1 } } );

官网上说不能用来匹配一个范围内的元素,如果想找$size<5之类的,他们建议创建一个字段来保存元素的数量。

You cannot use $size to find a range of sizes (for example: arrays with more than 1 element). If you need to query for a range, create an extra size field that you increment when you add elements.

7)$exists

$exists用来判断一个元素是否存在:

如:

代码语言:javascript
复制
db.things.find( { a : { $exists : true } } ); // 如果存在元素a,就返回
db.things.find( { a : { $exists : false } } ); // 如果不存在元素a,就返回
  1. $type

$type 基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。

代码语言:javascript
复制
db.things.find( { a : { $type : 2 } } ); // matches if a is a string
db.things.find( { a : { $type : 16 } } ); // matches if a is an int

9)正则表达式

mongo支持正则表达式,如:

代码语言:javascript
复制
db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写
  1. 查询数据内的值

下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。

代码语言:javascript
复制
db.things.find( { colors : "red" } );
  1. $elemMatch

如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素:

代码语言:javascript
复制
> t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } ) 
{ "_id" : ObjectId("4b5783300334000000000aa9"), 
"x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]
}$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。

注意,上面的语句和下面是不一样的。

> t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )
$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 }
  1. 查询嵌入对象的值
代码语言:javascript
复制
db.postings.find( { "author.name" : "joe" } );

注意用法是author.name,用一个点就行了。更详细的可以看这个链接: dot notation

举个例子:

db.blog.save({ title : “My First Post”, author: {name : “Jane”, id : 1}})

如果我们要查询 authors name 是Jane的, 我们可以这样:

db.blog.findOne({“author.name” : “Jane”})

如果不用点,那就需要用下面这句才能匹配:

代码语言:javascript
复制
db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})

下面这句:

代码语言:javascript
复制
db.blog.findOne({"author" : {"name" : "Jane"}})

是不能匹配的,因为mongodb对于子对象,他是精确匹配。

  1. 元操作符 $not 取反

如:

代码语言:javascript
复制
db.customers.find( { name : { $not : /acme.*corp/i } } );
db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } ); 

mongodb还有很多函数可以用,如排序,统计等,请参考原文。 mongodb目前没有或(or)操作符,只能用变通的办法代替。

代码语言:javascript
复制
左边是mongodb查询语句,右边是sql语句。对照着用,挺方便。  
db.users.find() select * from users  
db.users.find({"age" : 27}) select * from users where age = 27  
db.users.find({"username" : "joe", "age" : 27}) select * from users where "username" = "joe" and age = 27  
db.users.find({}, {"username" : 1, "email" : 1}) select username, email from users  
db.users.find({}, {"username" : 1, "_id" : 0}) // no case  // 即时加上了列筛选,_id也会返回;必须显式的阻止_id返回  
db.users.find({"age" : {"$gte" : 18, "$lte" : 30}}) select * from users where age >=18 and age <= 30 // $lt(<) $lte(<=) $gt(>) $gte(>=)  
db.users.find({"username" : {"$ne" : "joe"}}) select * from users where username <> "joe"  
db.users.find({"ticket_no" : {"$in" : [725, 542, 390]}}) select * from users where ticket_no in (725, 542, 390)  
db.users.find({"ticket_no" : {"$nin" : [725, 542, 390]}}) select * from users where ticket_no not in (725, 542, 390)  
db.users.find({"$or" : [{"ticket_no" : 725}, {"winner" : true}]}) select * form users where ticket_no = 725 or winner = true  
db.users.find({"id_num" : {"$mod" : [5, 1]}}) select * from users where (id_num mod 5) = 1  
db.users.find({"$not": {"age" : 27}}) select * from users where not (age = 27)  
db.users.find({"username" : {"$in" : [null], "$exists" : true}}) select * from users where username is null // 如果直接通过find({"username" : null})进行查询,那么连带"没有username"的纪录一并筛选出来  
db.users.find({"name" : /joey?/i}) // 正则查询,value是符合PCRE的表达式  
db.food.find({fruit : {$all : ["apple", "banana"]}}) // 对数组的查询, 字段fruit中,既包含"apple",又包含"banana"的纪录  
db.food.find({"fruit.2" : "peach"}) // 对数组的查询, 字段fruit中,第3个(从0开始)元素是peach的纪录  
db.food.find({"fruit" : {"$size" : 3}}) // 对数组的查询, 查询数组元素个数是3的记录,$size前面无法和其他的操作符复合使用  
db.users.findOne(criteria, {"comments" : {"$slice" : 10}}) // 对数组的查询,只返回数组comments中的前十条,还可以{"$slice" : -10}, {"$slice" : [23, 10]}; 分别返回最后10条,和中间10条  
db.people.find({"name.first" : "Joe", "name.last" : "Schmoe"})  // 嵌套查询  
db.blog.find({"comments" : {"$elemMatch" : {"author" : "joe", "score" : {"$gte" : 5}}}}) // 嵌套查询,仅当嵌套的元素是数组时使用,  
db.foo.find({"$where" : "this.x + this.y == 10"}) // 复杂的查询,$where当然是非常方便的,但效率低下。对于复杂查询,考虑的顺序应当是 正则 -> MapReduce -> $where  
db.foo.find({"$where" : "function() { return this.x + this.y == 10; }"}) // $where可以支持javascript函数作为查询条件  
db.foo.find().sort({"x" : 1}).limit(1).skip(10); // 返回第(10, 11]条,按"x"进行排序; 三个limit的顺序是任意的,应该尽量避免skip中使用large-number  

使用 $where 查询(性能稍逊一些)

代码语言:javascript
复制
//查询商品名称长度大于25个字符的商品
db.item.find({item_name:{$exists:true},$where:"(this.item_name.length > 25)"}).limit(5)
 
//查询商品名称长度小于5个字符的商品
db.item.find({$where:"this.item_name.length < 5"}).limit(5)

使用正则表达式查询(性能比$where 高)

代码语言:javascript
复制
//查询商品名称长度大于25个字符的商品
db.item.find({"item_name": {"$exists": true, "$regex": /^.{25,}$/}}).limit(5)   // 长度大于25
 
//查询商品名称长度小于5个字符的商品
db.item.find({"item_name": {"$regex": /^.{0,5}$/}}).limit(5)

参考:http://blog.163.com/ji_1006/blog/static/10612341201311271384351/ https://blog.csdn.net/qq_27093465/article/details/51700435

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018年07月11日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云数据库 MongoDB
腾讯云数据库 MongoDB(TencentDB for MongoDB)是腾讯云基于全球广受欢迎的 MongoDB 打造的高性能 NoSQL 数据库,100%完全兼容 MongoDB 协议,支持跨文档事务,提供稳定丰富的监控管理,弹性可扩展、自动容灾,适用于文档型数据库场景,您无需自建灾备体系及控制管理系统。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档