数据库会用到创建(create)读取(find)更新(update)删除(remove),MongoDB也同样会用到;
一、创建
用insert函数将文档添加到集合中。例如
创建数据库blog,将文档增加到集合post中(先将文档放入post的变量中)
> 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方法查看集合中的文档,例如
> 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赋值
> 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文档
> post.comments = [] [ ]
update方法更新集合
> 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方法删除文档
> db.post.remove({"title":"My blog post"}); WriteResult({ "nRemoved" : 1 }) > db.post.findOne(); null >
删除后post集合为空;
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。