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( , )
All queries in MongoDB address a single collection. 所有查询操作都在一个集合中进行。
ps:可以在数据库打开后,键入db指令,查看当前的数据库;键入show collections 查看所有的集合。
其中限制查询筛选条件,如果为空,则返回所有的文档(documents)。
限制返回的查询结果的域。 findOne()
findOne()不同之处:返回值类型为一个文档而不是游标(类似指针)。
具体语法如下:
db.collection.findOne( , )
Indexes索引
使用db.collection.ensureIndex()方法创建索引。
db.collection.ensureIndex( { : , : , ... } )
其中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中读取数据