> 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" : [ ]
}