本文主要介绍内容:从MongoDB中请求数据的不同的方法

Note:All of the examples in this document use the mongo shell interface. All of these operations are available in an idiomatic interface for each language by way of the MongoDB Driver. See your driver documentation for full API documentation.

Queries in MongoDB 查询

 find()

主要有find()和findOne()两种查询的方法,find()具体语法如下:

  db.collection.find( <query>, <projection> )

All queries in MongoDB address a single collection. 所有查询操作都在一个集合中进行。
ps:可以在数据库打开后,键入db指令,查看当前的数据库;键入show collections 查看所有的集合。

其中<query>限制查询筛选条件,如果为空,则返回所有的文档(documents)。
<projection>限制返回的查询结果的域。

findOne()
findOne()不同之处:返回值类型为一个文档而不是游标(类似指针)。

具体语法如下:
db.collection.findOne( <query>, <projection> )

Query Document
下面看一些<query>的例子:

   db.inventory.find( { type: 'food', price: { $lt: 9.95 } }, { item: 1, qty: 1 } )
在inventory集合中,查找type为food,price少于9.95的文档,返回这些文档的item和qty以及_id。该函数返回值类型为游标。
db.inventory.find({}) 查询集合中的所有文档,也能写成edb.inventory.find()。
db.inventory.find( { type: { $in: [ 'food', 'snacks' ] } } )筛选集合中type值为food或snacks的文档。

db.inventory.find( { $or: [ { qty: { $gt: 100 } },
                            { price: { $lt: 9.95 } } ]
                   } )筛选qty大于100或者price小于9.95的记录。
同一个域中的“或” 使用$in表示,不同域之间的“或”使用$or表示。

筛选子文档:
db.inventory.find( {
                     producer: {
                                 company: 'ABC123',
                                 address: '123 Street'
                               }
                   }
                 )
上面的例子可以使用点符号简化,如下:
db.inventory.find( { 'producer.company': 'ABC123' } )

筛选第一个子文档by域为shipping的所有的文档
db.inventory.find( { 'memos.0.by': 'shipping' } )

筛选至少有一个子文档by域为shipping的所有的文档
db.inventory.find( { 'memos.by': 'shipping' } )

Result Projections
下面看一些<projection>的例子:

结果包含item和qty域以及默认的_id域:
db.inventory.find( { type: 'food' }, { item: 1, qty: 1 } )

排除结果中默认的_id域:
db.inventory.find( { type: 'food' }, { item: 1, qty: 1, _id:0 } )

 
高级查询的补充知识:
摘自http://www.cnblogs.com/zhy4606/archive/2011/09/13/2175220.html
$all 匹配所有

这个操作符跟SQL语法的in类似,但不同的是, in只需满足( )内的某一个值即可,  而$all必须满足[ ]内的所有值,例如:
db.users.find({age : {$all : [6, 8]}});  
可以查询出  {name: 'David', age: 26, age: [ 6, 8, 9 ] }  
但查询不出  {name: 'David', age: 26, age: [ 6, 7, 9 ] }

$exists 判断字段是否存在

查询所有存在age字段的记录  
db.users.find({age: {$exists: true}});  
查询所有不存在name字段的记录  
db.users.find({name: {$exists: false}});
 
Null 值处理

> db.c2.find({age:null})

$mod 取模运算

查询age取模6等于1的数据
db.c1.find({age: {$mod : [ 6 , 1 ] } })

$ne 不等于
查询x的值不等于3 的数据
db.c1.find( { age : { $ne : 7 } } );

$in 包含
db.c1.find({age:{$in: [7,8]}});
 
$nin 不包含
查询age的值在7,8 范围外的数据 
db.c1.find({age:{$nin: [7,8]}});

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

正则表达式匹配

查询name 不以T开头的数据
db.c1.find({name: {$not: /^T.*/}});

Javascript 查询和$Where查询
查询a大于3的数据,下面的查询方法殊途同归
db.c1.find( { a : { $gt: 3 } } );
db.c1.find( { $where: "this.a > 3" } );
db.c1.find("this.a > 3");
f = function() { return this.a > 3; } db.c1.find(f);

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

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

Indexes索引

使用db.collection.ensureIndex()方法创建索引。
db.collection.ensureIndex( { <field1>: <order>, <field2>: <order>, ... } )

其中order选项,1表示升序,-1表示降序

The explain() cursor method allows you to inspect the operation of the query system, and is useful for analyzing the efficiency of queries, and for determining how the query uses the index.

db.inventory.find( { type: 'food' } ).explain()

可以通过查看描述,分析建立索引前后查询效率的变化。MongoDB使用B树建立索引。

Cursors游标

范例:
var myCursor = db.inventory.find( { type: 'food' } );
var myDocument = myCursor.hasNext() ? myCursor.next() : null;

if (myDocument) {
    var myItem = myDocument.item;
    printjson(myItem);
}

或者使用javascript语法:
var myCursor =  db.inventory.find( { type: 'food' } );

myCursor.forEach(printjson);

游标在10分钟后会自动回收,如果想要去除时间限制,设置如下:
var myCursor = db.inventory.find().addOption(DBQuery.Option.noTimeout);

Cursor Flags

mongo shell提供了以下cursor flags:

DBQuery.Option.tailable
    DBQuery.Option.slaveOk
    DBQuery.Option.oplogReplay
    DBQuery.Option.noTimeout
    DBQuery.Option.awaitData
    DBQuery.Option.exhaust
    DBQuery.Option.partial

集合操作(aggregation)

包括以下四种:
    count (count())
    distinct (db.collection.distinct())
    group (db.collection.group())
    mapReduce. (Also consider mapReduce() and Map-Reduce.)

从Sharded Clusters中读取数据

从Replica Sets中读取数据

MongoDB—— 读操作 Core MongoDB Operations (CRUD)的更多相关文章

  1. MongoDB—— 写操作 Core MongoDB Operations (CRUD)

    MongoDB使用BSON文件存储在collection中,本文主要介绍MongoDB中的写操作和优化策略. 主要有三种写操作:        Create        Update        ...

  2. NoSql数据库初探-mongoDB读操作

    MongoDB以文档的形式来存储数据,此结果类似于JSON键值对.文档类似于编程语言中将键和值关联起来的结构(比如:字典.Map.哈希表.关联数组).MongoDB文档是以BOSN文档的形式存在的.B ...

  3. .Net Core MongoDB 简单操作。

    一:MongoDB 简单操作类.这里引用了MongoDB.Driver. using MongoDB.Bson; using MongoDB.Driver; using System; using S ...

  4. MongoDB 读偏好设置中增加最大有效延迟时间的参数

    在某些情况下,将读请求发送给副本集的备份节点是合理的,例如,单个服务器无法处理应用的读压力,就可以把查询请求路由到可复制集中的多台服务器上.现在绝大部分MongoDB驱动支持读偏好设置(read pr ...

  5. 笔记-mongodb数据操作

    笔记-mongodb数据操作 1.      数据操作 1.1.    插入 db.COLLECTION_NAME.insert(document) 案例: db.inventory.insertOn ...

  6. MongoDB via Dotnet Core数据映射详解

    用好数据映射,MongoDB via Dotnet Core开发变会成一件超级快乐的事.   一.前言 MongoDB这几年已经成为NoSQL的头部数据库. 由于MongoDB free schema ...

  7. MongoDB常用操作一查询find方法db.collection_name.find()

    来:http://blog.csdn.net/wangli61289/article/details/40623097 https://docs.mongodb.org/manual/referenc ...

  8. mongodb高级操作及在Java企业级开发中的应用

    Java连接mongoDB Java连接MongoDB需要驱动包,个人所用包为mongo-2.10.0.jar.可以在网上下载最新版本. package org.dennisit.mongodb.st ...

  9. [置顶] MongoDB 分布式操作——分片操作

    MongoDB 分布式操作——分片操作 描述: 像其它分布式数据库一样,MongoDB同样支持分布式操作,且MongoDB将分布式已经集成到数据库中,其分布式体系如下图所示: 所谓的片,其实就是一个单 ...

随机推荐

  1. TcpClient类与TcpListener类

    TcpClient类 //构造方法1 TcpClient t = new TcpClient(); t.Connect(); //构造方法2 IPEndPoint iep = ); TcpClient ...

  2. Linux nginx 配置 location 语法 正则表达式

    location语法:location [=|~|~*|^~] /uri/ { - }默认:否上下文:server这个指令随URL不同而接受不同的结构.你可以配置使用常规字符串和正则表达式.如果使用正 ...

  3. 初识JSLint及建议JS编码风格

    可能都或多或少的知道JSLint是一个JavaScript的代码质量工具,一个JavaScript语法检查器和校验器,它能分析JavaScript问题并报告它包含的缺点. 被发现的问题往往是语法错误, ...

  4. [USACO2009 NOV GOLD]奶牛的图片

    校内题,不给传送门了. 以前做完NOIp2013的火柴排队那道题后,当时很担心NOIp会出那种题,因为贪心的规则能不能看出来真的要看运气.但是这类题做多了后发现其实那道题的规则其实是很多题都已经用到了 ...

  5. DNS(一)之禁用权威域名服务器递归解析

    DNS dns是互联网中最核心的带层级的分布式系统,负责把域名解析成ip,把IP解析出域名,以及宣告邮件路由信息等等,使得使用域名访问网站,收发邮件成了可能. bind(berkeley Intern ...

  6. HD2767Proving Equivalences(有向图强连通分量+缩点)

    题目链接 题意:有n个节点的图,现在给出了m个边,问最小加多少边是的图是强连通的 分析:首先找到强连通分量,然后把每一个强连通分量缩成一个点,然后就得到了一个DAG.接下来,设有a个节点(每个节点对应 ...

  7. 忘记常访问网站密码怎么办?教你如何查看浏览器已保存的密码,如何简单查看Chome浏览器保存的密码?

    利用场景: 同事或朋友外出有事,电脑未锁屏离开座位.可以利用这一间隙,查看Ta在Chrome浏览器上保存的账号密码 查看逻辑: 当我们要查看Chrome浏览器上保存的密码时,点击显示,会弹出一个对话框 ...

  8. 适可而止:YAGNI原则

    适可而止:You Ain't Gonna Need It YAGNI原则指的是只需要将应用程序必需的功能包含进来,而不要试图添加任何其他你认为可能需要的功能. 在一个软件项目中,往往80%的时间花费在 ...

  9. Jquery 实现密码框的显示与隐藏【转载自http://blog.csdn.net/fengzhishangsky/article/details/11809069】

    <html> <head>  <script type="text/JavaScript"  src="jQuery-1.5.1.min.j ...

  10. UDP 网络通信 C#

    接收端   using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Thre ...