目录
摘要
Query 结构,find,count,pretty,explain
Query
基本结构
db.users.find( //collection
{age: {$gt: 18}}, //query critria
{name: 1, address: 1} //projection
).limit(5) //cursor modifier
查找多条记录
db.<collectionName>.find([cond])
查找单条记录
db.<collectionName>.findOne([cond])
Shell 每次最多返回 20
条记录,可以输入 it
来获得更多记录。
查询结果集个数
db.<collectionName>.count()
Cursor
在 Shell 中除了可以直接使用 find()
,也可以使用 cursor 来保存检索结果。
var cursor = db.testData.find().addOption(DBQuery.Option.noTimout);
printjson(cursor[0])
格式化输出
在 find
语句后加上 pretty()
可以格式化输出查询结果。
Issue
迷惑的集合名
Javascript 只有在 db
的属性中中找不到与 collectionName 不符的属性时,才会将其作为集合返回。比如说 version 是 db 的一个属性,如果 collectionName 也为 version 的话,db.version
是不会正确返回的。此外 “foo-bar” 之类的不合法名也不会正确返回。
解决办法
db.getCollection(dbName)
explain
explain 可以用于分析查询语句的性能
db.towns.find().explain()