数据库会用到创建(create)读取(find)更新(update)删除(remove),MongoDB也同样会用到;
一、创建
用insert函数将文档添加到集合中。例如
创建数据库blog,将文档增加到集合post中(先将文档放入post的变量中)
1
2
3
4
5
|
> post={
"title"
:
"My blog post"
,
"context"
:
"Here's my blog post"
,
"date"
:new Date()}
> use blog
switched to db blog
> db.post.insert(post);
WriteResult({
"nInserted"
: 1 })
|
二、读取
用find方法或者findone方法查看集合中的文档,例如
1
2
3
4
5
6
7
8
9
10
|
> db.post.
find
()
{
"_id"
: ObjectId(
"54a50253e287e09898eab58b"
),
"title"
:
"My blog post"
,
"context"
:
"Here's my blog post"
,
"date"
: ISODate(
"2015-01-01T08:15:14.121Z"
) }
> db.post.findOne()
{
"_id"
: ObjectId(
"54a50253e287e09898eab58b"
),
"title"
:
"My blog post"
,
"context"
:
"Here's my blog post"
,
"date"
: ISODate(
"2015-01-01T08:15:14.121Z"
)
}
>
|
三、更新
重新给变量post赋值
1
2
3
4
5
6
7
8
9
|
> use blog
switched to db blog
> post=db.post.findOne()
{
"_id"
: ObjectId(
"54a50253e287e09898eab58b"
),
"title"
:
"My blog post"
,
"context"
:
"Here's my blog post"
,
"date"
: ISODate(
"2015-01-01T08:15:14.121Z"
)
}
|
给变量post增加一个comments文档
1
2
|
> post.comments = []
[ ]
|
update方法更新集合
1
2
3
4
5
6
7
8
9
10
|
> db.post.update({
"title"
:
"My blog post"
},post)
;WriteResult({
"nMatched"
: 1,
"nUpserted"
: 0,
"nModified"
: 1 })
> db.post.findOne()
{
"_id"
: ObjectId(
"54a50253e287e09898eab58b"
),
"title"
:
"My blog post"
,
"context"
:
"Here's my blog post"
,
"date"
: ISODate(
"2015-01-01T08:15:14.121Z"
),
"comments"
: [ ]
}
|
四、删除
用removed方法删除文档
1
2
3
4
5
|
> db.post.remove({
"title"
:
"My blog post"
});
WriteResult({
"nRemoved"
: 1 })
> db.post.findOne();
null
>
|
删除后post集合为空;
本文转自 bannerpei 51CTO博客,原文链接:http://blog.51cto.com/281816327/1598289,如需转载请自行联系原作者