第2章 MongoDB基础知识
2.1 文档
- MongoDB区分大小写,文档不能有相同的key
- \0是结束的标志,不能作为集合名或者key的名
2.2 集合
2.2.2 命名
- .和$是保留字
- 子集合,用 . 分隔
2.5 MongoDB shell简介
2.5.1 运行shell
2.5.2 MongoDB客户端
- db 查看所用数据库
- show dbs 查看数据库
- use db 使用某个数据库
- show collections 查看集合
2.5.3 shell种的基本操作
insert 创建
post = {
"title": "My Blog Post",
"content": "Here's my blog post",
"date": new Date()
}
db.blog.insert(post);
update 更新
post = {
"title": "My Blog Post",
"content": "Here's my blog post",
"date": new Date()
}
post.comments = [];
db.blog.update({title: "My Blog Post"}, post);
remove 删除
db.blog.remove(query) //没有query会全部删除
2.6 数据类型
2.6.1 基本数据类型
- null
null 用于表示空值或者不存在的字段
js{"x" : null}
- boolean
{"x" : true}
- number
The shell defaults to using 64-bit floating point numbers. Thus, these numbers look
“normal” in the shell:
{
"x" : 3.14}
//or:
{
"x" : 3}
For integers, use the NumberInt or NumberLong classes, which represent 4-byte or
8-byte signed integers, respectively.
{
"x" : NumberInt("3")}
{
"x" : NumberLong("3")}
- string
Any string of UTF-8 characters can be represented using the string type:
{"x" : "foobar"}
- date
Dates are stored as milliseconds since the epoch. The time zone is not stored:
{"x" : new Date()}
- regular expression
Queries can use regular expressions using JavaScript’s regular expression syntax:
{"x" : /foobar/i}
- array
Sets or lists of values can be represented as arrays:
{"x" : ["a", "b", "c"]}
- embedded document 内嵌文档
Documents can contain entire documents embedded as values in a parent
document:
{"x" : {"foo" : "bar"}}
Data Types | 17
Download from Wow! eBook
2.6.2 日期
2.6.3 数组
查询的时候,可以查询数组里的某个元素
存在users:[‘1261651’,’321321354’]
例如query={users: ‘15915154578’}
2.6.4 内嵌文档
2.6.5 _id和ObjectId
- _id 在集合中必须唯一,是ObjectId对象
- 创建文档没有_id键的时候系统会帮你创建一个
2.7 使用MongoDB shell
2.7.4 定制shell提示
第3章 创建、更新和删除文档
3.1插入并保存文档
> db.foo.insert({bar:"barz"})
3.1.1 批量插入
- batchInsert
> db.foo.batchInsert([{},{},{}])
- continueOnError 选项
3.1.2 插入校验
- 16M 当前文档最大值
- 容易插入非法值
3.2删除文档
- remove(query)
- 不能撤销,不能恢复
//插入100万条数据
for(var