MongoDB—— 读操作 Core MongoDB Operations (CRUD)
本文主要介绍内容:从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 } )
这个操作符跟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)的更多相关文章
- MongoDB—— 写操作 Core MongoDB Operations (CRUD)
MongoDB使用BSON文件存储在collection中,本文主要介绍MongoDB中的写操作和优化策略. 主要有三种写操作: Create Update ...
- NoSql数据库初探-mongoDB读操作
MongoDB以文档的形式来存储数据,此结果类似于JSON键值对.文档类似于编程语言中将键和值关联起来的结构(比如:字典.Map.哈希表.关联数组).MongoDB文档是以BOSN文档的形式存在的.B ...
- .Net Core MongoDB 简单操作。
一:MongoDB 简单操作类.这里引用了MongoDB.Driver. using MongoDB.Bson; using MongoDB.Driver; using System; using S ...
- MongoDB 读偏好设置中增加最大有效延迟时间的参数
在某些情况下,将读请求发送给副本集的备份节点是合理的,例如,单个服务器无法处理应用的读压力,就可以把查询请求路由到可复制集中的多台服务器上.现在绝大部分MongoDB驱动支持读偏好设置(read pr ...
- 笔记-mongodb数据操作
笔记-mongodb数据操作 1. 数据操作 1.1. 插入 db.COLLECTION_NAME.insert(document) 案例: db.inventory.insertOn ...
- MongoDB via Dotnet Core数据映射详解
用好数据映射,MongoDB via Dotnet Core开发变会成一件超级快乐的事. 一.前言 MongoDB这几年已经成为NoSQL的头部数据库. 由于MongoDB free schema ...
- MongoDB常用操作一查询find方法db.collection_name.find()
来:http://blog.csdn.net/wangli61289/article/details/40623097 https://docs.mongodb.org/manual/referenc ...
- mongodb高级操作及在Java企业级开发中的应用
Java连接mongoDB Java连接MongoDB需要驱动包,个人所用包为mongo-2.10.0.jar.可以在网上下载最新版本. package org.dennisit.mongodb.st ...
- [置顶] MongoDB 分布式操作——分片操作
MongoDB 分布式操作——分片操作 描述: 像其它分布式数据库一样,MongoDB同样支持分布式操作,且MongoDB将分布式已经集成到数据库中,其分布式体系如下图所示: 所谓的片,其实就是一个单 ...
随机推荐
- Logistic Regression分类器
1. 两类Logistic回归 Logistic回归是一种非常高效的分类器.它不仅可以预测样本的类别,还可以计算出分类的概率信息. 不妨设有$n$个训练样本$\{x_1, ..., x_n\}$,$x ...
- iOS - CAEmitterLayer流星
效果图: 流星: #pragma mark - loading animation - (void)showLoadingAnimation { CGRect mainBounds = [[UIScr ...
- java函数substring()
String str; str=str.substring(int beginIndex);截取掉str从首字母起长度为beginIndex的字符串,将剩余字符串赋值给str: str=str.sub ...
- gcc编译与gdb调试简要步骤
http://blog.chinaunix.net/uid-24103300-id-108248.html 一.Linux程序gcc编译步骤: Gcc编译过程主要的4个阶段: l 预处理阶段,完成宏定 ...
- 多态 oc c++ 与oc category
多态是函数调用的动态绑定技术: c++动态绑定依赖于this指针与虚函数表. 虚函数表的排序规则: 1)虚函数按照其声明顺序放于表中. 2)父类的虚函数在子类的虚函数前面. 3)如果子类重写了父类的虚 ...
- bootstrap标签引入地址
http://www.bootcdn.cn/bootstrap/ <link rel="stylesheet" href="http://apps.bdimg.co ...
- Win8下安装.Net3.5的完美策略
在Win8中运行之前的.Net版本(4.0以下)写的程序时,会出现需要安装.Net 3.5的提示.但是你使用在线安装的话是无法成功的,在线升级会遇到错误0x800F0906.明明Win8系统集成的是. ...
- Maven入门学习,安装及创建项目
一.maven介绍: 1.maven是一个基于项目对象模型(POM Project Object Model),通过配置文件管理项目的工具(项目管理工具). 2.maven主要功能:发布项目(从编译到 ...
- (转)Java字符串
转自:http://blog.sina.com.cn/s/blog_899678b90101brz0.html 创建字符串有两种方式:两种内存区域(字符串池,堆)1," " 引号创 ...
- C#----XML操作小结
结点和元素的区别: * 结点和元素的区别: * 结点包括元素,结点可以是一个文本,也可以是一个属性,结点包括的类型在XmlNodeType中总结. * <root id="这是一个 ...