操作MongoDB数据库之前先要启动MongoDB客户端shell,方法见上一篇博客MongoDB的使用。
这个shell是个功能完备的JavaScript解释器,可以在上面运行任何JavaScript程序。
但其主要的作用是作为MongoDB客户端,通过它对MongoDB数据库进行管理。
以下列举常用的操作和命令:
(1)选择或创建需要操作的数据库:use
use bookshelf
(2)插入数据:向集合中插入一个文档:db.bookshelf.insert()
book = { "title": "MongoDB in Action", "author": "DBA", "published": "2012-12-21" }; db.bookshelf.insert(book);
(3)读取数据
db.bookshelf.find()
db.bookshelf.findOne()
(4)更新数据:db.bookshelf.update()
book.author = "winstar" db.bookshelf.update({title: "MongoDB in Action"}, book)
(5)删除数据:db.bookshelf.remove()
db.bookshelf.remove({author: "winstar"})