【有书共读】MongoDB实战第二版第二章
通过Javascript shell操作MongoDB
macOs 安装MongoDB
1.更新 Homebrew的package数据库(macosx上的软件包管理工具)
$ brew update
2.安装MongoDb
$ brew install mongodb
3.启动MongoDb
$ brew services start mongodb
4.连接到mongo
$ mongo
5.关闭MongoDb
$ brew services stop mongodb
如果安装过程遇到如下错误
Error: An unexpected error occurred during the `brew link` step
The formula built, but is not symlinked into /usr/local
Permission denied @ dir_s_mkdir - /usr/local/Frameworks
Error: Permission denied @ dir_s_mkdir - /usr/local/Frameworks
执行以下命令
sudo chown -R $(whoami) $(brew --prefix)/*
sudo install -d -o $(whoami) -g admin /usr/local/Frameworks
数据库,集合和文档
mongoDB把数据储存在文档中,数据可以以Json的格式输出。我们可以在不同的地方储存不同的文档,如文档usrs 和orders,一些文档以某种方式分类,成为集合,我们把集合储存在不同的数据库中。
切换数据库
> use tutorial
switched to db tutorial
创建第一个文档,因为使用javascript shell,文档使用JSON
> {username: "smith"}
smith
插入和查询
插入文档需要指定插入的集合,我们选择users集合
> db.users.insert({username: "smith"})
WriteResult({ "nInserted" : 1 })
如果插入成功,就成功保存了第一个文档
> db.users.find()
{ "_id" : ObjectId("5c00fba91fa39c550ae90b8d"), "username" : "smith" }
_id是文档的主键
继续插入
> db.users.insert({username: "john"})
WriteResult({ "nInserted" : 1 })
> db.users.count()
2
> db.users.find()
{ "_id" : ObjectId("5c00fba91fa39c550ae90b8d"), "username" : "smith" }
{ "_id" : ObjectId("5c00fc831fa39c550ae90b8e"), "username" : "john" }
> db.users.find({username: "john"})
{ "_id" : ObjectId("5c00fc831fa39c550ae90b8e"), "username" : "john" }
可以多个条件查询
> db.users.find({ "_id" : ObjectId("5c00fc831fa39c550ae90b8e"), "username" : "john" })
{ "_id" : ObjectId("5c00fc831fa39c550ae90b8e"), "username" : "john" }
等价于使用$and
> db.users.find({$and: [{"_id" : ObjectId("5c00fc831fa39c550ae90b8e")}, {"username" : "john"}]})
{ "_id" : ObjectId("5c00fc831fa39c550ae90b8e"), "username" : "john" }
也可以使用$or来进行或查询
> db.users.find({$or: [{"username" : "smith"}, {"username" : "john"}]})
{ "_id" : ObjectId("5c00fba91fa39c550ae90b8d"), "username" : "smith" }
{ "_id" : ObjectId("5c00fc831fa39c550ae90b8e"), "username" : "john" }
更新
指定文档,指定更新内容。注意使用$set,表示是更新当前文档
> db.users.update({username:"smith"},{$set: {country: "usa"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
想要删除country,使用$unset
> db.users.update({username:"smith"},{$unset: {country: 1}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.users.update({username:"smith"},{$set: {favorites:{movies: ["movie1", "movie2"]}}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.users.find({username:"smith"}).pretty()
{
"_id" : ObjectId("5c00fba91fa39c550ae90b8d"),
"username" : "smith",
"country" : "usa",
"favorites" : {
"movies" : [
"movie1",
"movie2"
]
}
}
删除
> db.users.remove({username:"smith"})
WriteResult({ "nRemoved" : 1 })
删除整个文档用drop
#MongoDB#