千家信息网

典型NoSQL数据库的安装和使用——MongoDB安装和使用

发表于:2024-10-20 作者:千家信息网编辑
千家信息网最后更新 2024年10月20日,安装方式采用apt-get install mongodb命令直接进行,采用源码包安装也可以hadoop@dblab:/$ sudo apt-get updatehadoop@dblab:/$ sud
千家信息网最后更新 2024年10月20日典型NoSQL数据库的安装和使用——MongoDB安装和使用

安装方式

采用apt-get install mongodb命令直接进行,采用源码包安装也可以

hadoop@dblab:/$ sudo apt-get update

hadoop@dblab:/$ sudo apt-get install -y mongodb-org

hadoop@dblab:/$ mongo -version

MongoDB shell version: 3.2.22

hadoop@dblab:/$ sudo service mongodb start #启动MongoDB

hadoop@dblab:/$ mongo #进入MongoDB Shell模式

> use school #切换到shcool数据库,使用时会自动创建

switched to db school

> db.createCollection('teacher') #创建集合

{ "ok" : 1 }

> show dbs #显示数据库列表

local 0.000GB

school 0.000GB

> db.student.insert({_id:1,sname:'zhangsan',sage:20}) #插入数据

WriteResult({ "nInserted" : 1 })

> db.student.insert({_id:2,sname:'lisi',sage:22}) #插入数据

WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : 2 })

> use school

switched to db school

> show collections #显示当前数据库的集合

student

teacher

#查找数据

> db.student.find() #查找所有记录

{ "_id" : 1, "sname" : "lisi", "sage" : 22 }

{ "_id" : 2, "sname" : "lisi", "sage" : 22 }

> db.student.remove({_id: 2}) #删除数据

WriteResult({ "nRemoved" : 1 })

> db.student.find()

{ "_id" : 1, "sname" : "lisi", "sage" : 22 }

> db.student.insert({_id:2,sname:'zhangsan',sage:25})

WriteResult({ "nInserted" : 1 })

> db.student.find()

{ "_id" : 1, "sname" : "lisi", "sage" : 22 }

{ "_id" : 2, "sname" : "zhangsan", "sage" : 25 }

>

#修改数据

> db.student.update({_id:2},{$set:{sage:88}},false,true)

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.student.find().pretty()

{ "_id" : 1, "sname" : "lisi", "sage" : 22 }

{ "_id" : 2, "sname" : "zhangsan", "sage" : 88 }

#删除数据

> db.student.remove({sname:'lisi'})

WriteResult({ "nRemoved" : 1 })

#删除集合

> db.student.drop()

> show collections

teacher

> exit #退出MongoDB Shell模式

bye

0