这篇是看MongoDB The Definitive Guide 的阅读记录,并没有太多细节知识点,只是用来梳理我都读了什么。
MongoDB以及其它的数据库在我现在的理解看来,最主要的操作就是insert,update,remove和query四种。
而其中最核心的就是 insert 和 query。因为update 和 remove 其实也是基于query 的结果之上的。
条件查询:
<, <=, >=, > : "$lt", "$lte", "$gt", "$gte"
not equal: "$ne"
mod模:"$mod"
OR/AND 查询:
"$in", "$or", "$nin", "$nor", "$not", "$and"
null 值为null或键不存在:
db.collection.find({"name": null})
键存在:
"$exists"
正则表达式:
MongoDB用Perl的正则表达式语法(Perl Compatible Regular Expression(PCRE))
可以用以匹配字符串或者直接匹配直接以RE为值的键。
列表查询:
列表中是否含以下所有元素:
"$all"
列表大小:
"$size"
find()的第二个参数的切片操作:
"$slice"
对列表中元素进行多个条件查询时:
"$elemMatch" :用来将每个条件都代入同一元素。如果不用,则只要每一条件能匹配列表中的任一元素就算匹配成功。
内嵌文档查询:
用 "." 来匹配文档中的键:
"name.first", "name.last"
复杂查询:
"$where":用JavaScript
Cursors:
var cursor = db.collection.find()
cursor.hasNext()
cursor.next()
用来控制查询的结果,包括limit,sort,skip.
db.c.find().limit(3)
db.c.find().skip(3)
db.c.find().sort({username:!,age:-1})
分页:(pagination):
db.stock.find({"desc":"mp3"}).limit(50).skip(50).sort({"price":-1})
避免大量skips:
while (page1.hasNext()){
latest = page1.next();
display(latest);
}
var page2 = db.foo.find({"date":{"$gt":latest.date}});
page2.sort({"date":-1}).limit(100);
find随机文件
一个方法:insert时插入随机数:
db.people.insert({"name":"joe","random":Math.random()})
高级查询选项:
两种查询类型:wrapped 和 plain
plain:
var cursor = db.foo.find({"foo":"bar"})
wrap:
var cursor = db.foo.find({"foo":"bar"}).sort({"x":1})
其它选项
$maxscan, $min, $max, $showDiskLoc
减少数据复写:
db.foo.snapshot()
数据库命令:
db.runCommand({"drop":"test"});
db.test.drop()
db.runCommand({getLastError:1})
db.adminCommand({"shutdown":1})