`

MongoDB高级查询用法大全

 
阅读更多

详见官方的手册:

http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-ConditionalOperators%3A%3C%2C%3C%3D%2C%3E%2C%3E%3D


版本一:

1 ) . 大于,小于,大于或等于,小于或等于

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

例子:

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:

db.things.find({j : {$lt: 3}});
db.things.find({j : {$gte: 4}});

也可以合并在一条语句内:

db.collection.find({ "field" : { $gt: value1, $lt: value2 } } );    // value1 < field < value

 

 

2) 不等于 $ne

例子:

db.things.find( { x : { $ne : 3 } } );

 

 

3) in 和 not in ($in $nin)

语法:

db.collection.find( { "field" : { $in : array } } );

例子:

db.things.find({j:{$in: [2,4,6]}});
db.things.find({j:{$nin: [2,4,6]}});


4) 取模运算$mod

如下面的运算:

db.things.find( "this.a % 10 == 1")

可用$mod代替:

db.things.find( { a : { $mod : [ 10 , 1 ] } } )


5)  $all

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

如有一个对象:

{ a: [ 1, 2, 3 ] }

下面这个条件是可以匹配的:

db.things.find( { a: { $all: [ 2, 3 ] } } );

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

db.things.find( { a: { $all: [ 2, 3, 4 ] } } );


6)  $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用来判断一个元素是否存在:

如:

db.things.find( { a : { $exists : true } } ); // 如果存在元素a,就返回
db.things.find( { a : { $exists : false } } ); // 如果不存在元素a,就返回

8)  $type

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

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支持正则表达式,如:

db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写

10)  查询数据内的值

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

db.things.find( { colors : "red" } );

11) $elemMatch

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

> 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 } 

12)  查询嵌入对象的值

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"})

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

db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})

下面这句:

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

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

 

13) 元操作符 $not 取反

如:

db.customers.find( { name : { $not : /acme.*corp/i } } );
db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } );

 

mongodb还有很多函数可以用,如排序,统计等,请参考原文。

mongodb目前没有或(or)操作符,只能用变通的办法代替,可以参考下面的链接:

http://www.mongodb.org/display/DOCS/OR+operations+in+query+expressions

版本二:

shell 环境下的操作:

   1.  超级用户相关:

         1. #进入数据库admin

             use admin

         2. #增加或修改用户密码

          db.addUser('name','pwd')

         3. #查看用户列表

          db.system.users.find()

         4. #用户认证

          db.auth('name','pwd')

         5. #删除用户

          db.removeUser('name')

         6. #查看所有用户

          show users

         7. #查看所有数据库

          show dbs

         8. #查看所有的collection

          show collections

         9. #查看各collection的状态

          db.printCollectionStats()

        10. #查看主从复制状态

          db.printReplicationInfo()

        11. #修复数据库

          db.repairDatabase()

        12. #设置记录profiling,0=off 1=slow 2=all

          db.setProfilingLevel(1)

        13. #查看profiling

          show profile

        14. #拷贝数据库

          db.copyDatabase('mail_addr','mail_addr_tmp')

        15. #删除collection

          db.mail_addr.drop()

        16. #删除当前的数据库

          db.dropDatabase()

   2. 增删改

         1. #存储嵌套的对象

             db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})

         2. #存储数组对象

             db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})

         3. #根据query条件修改,如果不存在则插入,允许修改多条记录

            db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)

         4. #删除yy=5的记录

            db.foo.remove({'yy':5})

         5. #删除所有的记录

            db.foo.remove()

   3. 索引

         1. #增加索引:1(ascending),-1(descending)

         2. db.foo.ensureIndex({firstname: 1, lastname: 1}, {unique: true});

         3. #索引子对象

         4. db.user_addr.ensureIndex({'Al.Em': 1})

         5. #查看索引信息

         6. db.foo.getIndexes()

         7. db.foo.getIndexKeys()

         8. #根据索引名删除索引

         9. db.user_addr.dropIndex('Al.Em_1')

   4. 查询

         1. #查找所有

        2. db.foo.find()

        3. #查找一条记录

        4. db.foo.findOne()

        5. #根据条件检索10条记录

        6. db.foo.find({'msg':'Hello 1'}).limit(10)

        7. #sort排序

        8. db.deliver_status.find({'From':'ixigua@sina.com'}).sort({'Dt',-1})

         9. db.deliver_status.find().sort({'Ct':-1}).limit(1)

        10. #count操作

        11. db.user_addr.count()

        12. #distinct操作,查询指定列,去重复

        13. db.foo.distinct('msg')

        14. #”>=”操作

        15. db.foo.find({"timestamp": {"$gte" : 2}})

        16. #子对象的查找

        17. db.foo.find({'address.city':'beijing'})

   5. 管理

         1. #查看collection数据的大小

         2. db.deliver_status.dataSize()

         3. #查看colleciont状态

         4. db.deliver_status.stats()

         5. #查询所有索引的大小

         6. db.deliver_status.totalIndexSize()

 

6.  高级查询

条件操作符 
$gt : > 
$lt : < 
$gte: >= 
$lte: <= 
$ne : !=、<> 
$in : in 
$nin: not in 
$all: all 
$not: 反匹配(1.3.3及以上版本) 

查询 name <> "bruce" and age >= 18 的数据 
db.users.find({name: {$ne: "bruce"}, age: {$gte: 18}}); 

查询 creation_date > '2010-01-01' and creation_date <= '2010-12-31' 的数据 
db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)}); 

查询 age in (20,22,24,26) 的数据 
db.users.find({age: {$in: [20,22,24,26]}}); 

查询 age取模10等于0 的数据 
db.users.find('this.age % 10 == 0'); 
或者 
db.users.find({age : {$mod : [10, 0]}}); 

匹配所有 
db.users.find({favorite_number : {$all : [6, 8]}}); 
可以查询出{name: 'David', age: 26, favorite_number: [ 6, 8, 9 ] } 
可以不查询出{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] } 

查询不匹配name=B*带头的记录 
db.users.find({name: {$not: /^B.*/}}); 
查询 age取模10不等于0 的数据 
db.users.find({age : {$not: {$mod : [10, 0]}}}); 

#返回部分字段 
选择返回age和_id字段(_id字段总是会被返回) 
db.users.find({}, {age:1}); 
db.users.find({}, {age:3}); 
db.users.find({}, {age:true}); 
db.users.find({ name : "bruce" }, {age:1}); 
0为false, 非0为true 

选择返回age、address和_id字段 
db.users.find({ name : "bruce" }, {age:1, address:1}); 

排除返回age、address和_id字段 
db.users.find({}, {age:0, address:false}); 
db.users.find({ name : "bruce" }, {age:0, address:false}); 

数组元素个数判断 
对于{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }记录 
匹配db.users.find({favorite_number: {$size: 3}}); 
不匹配db.users.find({favorite_number: {$size: 2}}); 

$exists判断字段是否存在 
查询所有存在name字段的记录 
db.users.find({name: {$exists: true}}); 
查询所有不存在phone字段的记录 
db.users.find({phone: {$exists: false}}); 

$type判断字段类型 
查询所有name字段是字符类型的 
db.users.find({name: {$type: 2}}); 
查询所有age字段是整型的 
db.users.find({age: {$type: 16}}); 

对于字符字段,可以使用正则表达式 
查询以字母b或者B带头的所有记录 
db.users.find({name: /^b.*/i}); 

$elemMatch(1.3.1及以上版本) 
为数组的字段中匹配其中某个元素 

Javascript查询和$where查询 
查询 age > 18 的记录,以下查询都一样 
db.users.find({age: {$gt: 18}}); 
db.users.find({$where: "this.age > 18"}); 
db.users.find("this.age > 18"); 
f = function() {return this.age > 18} db.users.find(f); 

排序sort() 
以年龄升序asc 
db.users.find().sort({age: 1}); 
以年龄降序desc 
db.users.find().sort({age: -1}); 

限制返回记录数量limit() 
返回5条记录 
db.users.find().limit(5); 
返回3条记录并打印信息 
db.users.find().limit(3).forEach(function(user) {print('my age is ' + user.age)}); 
结果 
my age is 18 
my age is 19 
my age is 20 

限制返回记录的开始点skip() 
从第3条记录开始,返回5条记录(limit 3, 5) 
db.users.find().skip(3).limit(5); 

查询记录条数count() 
db.users.find().count(); 
db.users.find({age:18}).count(); 
以下返回的不是5,而是user表中所有的记录数量 
db.users.find().skip(10).limit(5).count(); 
如果要返回限制之后的记录数量,要使用count(true)或者count(非0) 
db.users.find().skip(10).limit(5).count(true); 

分组group() 
假设test表只有以下一条数据 
{ domain: "www.mongodb.org" 
, invoked_at: {d:"2009-11-03", t:"17:14:05"} 
, response_time: 0.05 
, http_action: "GET /display/DOCS/Aggregation" 

使用group统计test表11月份的数据count:count(*)、total_time:sum(response_time)、avg_time:total_time/count; 
db.test.group( 
{ cond: {"invoked_at.d": {$gt: "2009-11", $lt: "2009-12"}} 
, key: {http_action: true} 
, initial: {count: 0, total_time:0} 
, reduce: function(doc, out){ out.count++; out.total_time+=doc.response_time } 
, finalize: function(out){ out.avg_time = out.total_time / out.count } 
} ); 



"http_action" : "GET /display/DOCS/Aggregation", 
"count" : 1, 
"total_time" : 0.05, 
"avg_time" : 0.05 

]
分享到:
评论

相关推荐

    MongoDB 高级查询 aggregate 聚合管道

    db.COLLECTION_NAME.aggregate() 方法用来构建和使用聚合管道,下图是官网给的实例,可以看出来聚合管道的用法还是比较简单的。   2. MongoDB Aggregation 管道操作符与表达式 常用的管道操作符有以下这些: ...

    MongoDB查询之高级操作详解(多条件查询、正则匹配查询等)

    MongoDB查询文档使用find()方法,同时find()方法以非结构化的方式来显示所有查询到的文档。 -- 1.基本语法 db.collection.find(query, projection) -- 返回所有符合查询条件的文档 db.collection.findOne(query, ...

    深入云计算 MongoDB管理与开发实战详解pdf.part1

    详细而深入,对MongoDB的开发和管理方法进行了详细的讲解,也对MongoDB的工作机制进行了深入的探讨。注重实战,通过实际中的案例为读者讲解使用MongoDB时遇到的各种问题,并给出了解决方案。本书旨在帮助云计算初学...

    MongoDB权威指南(中文版)高清

    494.3.1 null 494.3.2 正则表达式 504.3.3 查询数组 514.3.4 查询内嵌文档 534.4 $where查询 554.5 游标 564.5.1 limit、skip和sort 574.5.2 避免使用skip略过大量结果 584.5.3 高级查询选项 604....

    mongodb的高级使用

    NULL 博文链接:https://fengzhongdengdai.iteye.com/blog/2039779

    电子书:MongoDB权威指南(中文版)

    514.3.4 查询内嵌文档 534.4 $where 查询 554.5 游标 564.5.2 避免使用skip 略过大量结果 584.5.3 高级查询选项 604.5.4 获取一致结果 614.6 游标内幕 63第5 章 索引 655.1 索引简介 655.1.1 ...

    mongodb-mock:模拟你的mongodb

    mongodb-mock 模拟你的mongodb问题您的基础架构团队不想安装或配置CI / CD管道以使mongodb运行,​​您最终会使用某个模块尝试运行mongodb中实现的所有操作,但是该模块无法处理高级查询和令人沮丧的问题开始......

    api-query-params:将URL查询参数转换为MongoDB查询

    api查询参数 将查询参数从API网址转换为MongoDB查询(高级查询,过滤,排序等)产品特点功能强大。 支持大多数MongoDB运算符( $in , $regexp …)和功能(嵌套对象,投影,类型转换等) 自定义。 允许自定义键(即...

    深入云计算 MongoDB管理与开发实战详解pdf.part2

    详细而深入,对MongoDB的开发和管理方法进行了详细的讲解,也对MongoDB的工作机制进行了深入的探讨。注重实战,通过实际中的案例为读者讲解使用MongoDB时遇到的各种问题,并给出了解决方案。本书旨在帮助云计算初学...

    mongodb_the_definitive_guide_2nd_edition.pdf

    第二部分介绍使用MongoDB进行开发,包括索引的概念以及各种特殊索引和集合的用法等。第三部分讲述复制,包括副本集的相关概念、创建方法,与应用程序的交互等。第四部讨论分片,包括分片的配置,片键的选择,集群的...

    mongo-php-library:MongoDB PHP库

    如果要使用MongoDB开发应用程序,则应考虑使用此库或其他高级抽象,而不是单独使用扩展。 有关此库的体系结构和mongodb扩展的其他信息,可以在找到。文献资料 安装安装此库的首选方法是通过从项目根目录运行以下...

    mongo-experiments:我将使用Docker,DockerCompose,MongoDB和Golang改善我的MongoDBGolang技能的个人项目

    我决定创建一个存储库,使我可以在MongoDB中练习基本/高级查询,因此我创建了一个REST API来测试其中一些查询,其余的将在工作簿文件夹中的单独文件中找到,因为我将插入他们直接进入Mongo控制台。 我使用Docker为...

    mongate:使用 mongate 启动您的 nodejs 应用程序以访问 mongodb

    mongate 的灵感来自需要具有 node-mongodb-native apis 的高级接口。 这消除了本地访问 mongodb 的大部分复杂性和混乱。 文档 在研究 (一种在营销和销售中注入社交网络的方法)时,我意识到显然需要对库进行包装以...

    Spring高级之注解驱动开发视频教程

    从应用场景分析,到基本用法的入门案例,再到高级特性的分析及使用,最后是执行原理的源码分析。让学生通过学习本套课程不仅可以知其然,还可以知其所以然。最终通过一个综合案例,实现灵活运用Spring框架中的各个...

    适用于R的快速简单的MongoDB客户端-C/C++开发

    适用于R的mongolite快速,简单的MongoDB客户端基于libmongoc和jsonlite的高级,高性能MongoDB客户端。 包括对聚合,索引编制,映射减少,流式传输,SSL加密的支持,一个用于R的mongolite快速简单MongoDB客户端基于...

    MongoRepository:官方MongoDB C#驱动程序之上的存储库抽象层

    请查看以获取分步示例和更高级的用法。 例: // The Entity base-class is provided by MongoRepository // for all entities you want to use in MongoDb public class Customer : Entity { public string ...

    node-mongo:Node Mongo —是对MongoDB API的React式扩展

    用法连接到MongoDB const connectionString = 'mongodb://localhost:27017/home-db' ;const db = require ( '@paralect/node-mongo' ) . connect ( connectionString ) ;CRUD操作// create a service to work with ...

    nestjs-graphql-最佳实践:NestJS(Express + TypeORM + GraphQL + MongoDB)代码库,其中包含实际示例(CRUD,auth,高级模式等)

    NestJS(Express + Typeorm)代码库,其中包含实际示例(CRUD,auth,高级模式等)。 目录 结构体 功能 动态导入 认证 像OAuth一样配置jwt(access-token,refresh-token) OAuth Google OAuth Facebook 转储...

    xenus:一个简单而优雅的MongoDB ODM

    )进行自我记录它包括更新,删除和插入文档( )的流利方法它支持通过高级语法( )嵌入它开箱即处理关系( ) 它为您的API资源( )提供了完善的转换层机制如果您正在使用Laravel或Lumen框架,请查看集成。...

Global site tag (gtag.js) - Google Analytics