1 MongoDB 日常操作
1.1 创建数据库
创建studentService,并show所有数据库
> use studentService
switched to db studentService
> db
studentService
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
1.2 插入数据
发现没有显示studentService,是因为MongoDB不显示空的db,要想显示,需要插入些数据
> db.studentService.insert({"name":"Weison"})
WriteResult({ "nInserted" : 1 })
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
studentService 0.000GB
1.3 刷新客户端
这是刷新客户端连接工具,就可以看到studentService和表了
1.4 往集合中插数据
> db.students.insert({"name":"Weison","sex":"男"})
WriteResult({ "nInserted" : 1 })
> db.scores.insert({"name":"Weison","score":"98"})
WriteResult({ "nInserted" : 1 })
> show collections
score
scores
studentService
students
1.5 删除集合
> db.score.drop()
true
> db.studentService.drop()
true
> show collections
scores
students
1.6 更新集合
> db.students.update({'name':'Weison'},{$set:{'phoneNum':18702966632}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.students.find().pretty()
{
"_id" : ObjectId("5cff41a9c88cf469cc121da9"),
"name" : "Weison",
"sex" : "男",
"phoneNum" : 18702966632
}
1.7 更新多个数据
> db.students.update({'sex':'男'},{$set:{'describe':'this is a man'}},{multi:true})
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })
> db.students.find().pretty()
{
"_id" : ObjectId("5cff41a9c88cf469cc121da9"),
"name" : "Weison",
"sex" : "男",
"phoneNum" : 18702966632,
"describe" : "this is a man"
}
{
"_id" : ObjectId("5cff42fcc88cf469cc121dab"),
"name" : "Lucas",
"sex" : "男",
"describe" : "this is a man"
}
1.8 删除数据
> db.students.remove({'name':'Jac'})
WriteResult({ "nRemoved" : 1 })
> db.students.remove({'name':'Jack'})
WriteResult({ "nRemoved" : 1 })
1.9 创建索引
> db.students.createIndex({'stId':1})
{
"createdCollectionAutomatically" : false,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
1.10 以优雅的姿势展示结果
> db.students.find().pretty()
{
"_id" : ObjectId("5cff41a9c88cf469cc121da9"),
"name" : "Weison",
"sex" : "男",
"phoneNum" : 18702966632,
"describe" : "this is a man"
}
{
"_id" : ObjectId("5cff42fcc88cf469cc121dab"),
"name" : "Lucas",
"sex" : "男",
"describe" : "this is a man"
}
{
"_id" : ObjectId("5cff4647c88cf469cc121db0"),
"name" : "Jack",
"sex" : "男"
}