安装完成MongoDB,了解一下MongoDB的基础知识
2 MongoDB基本命令
show dbs – 列出所有的数据库
use db_name – 切换到数据库db_name
showcollections –- 列出所有在当前数据库中的表名
db.help()/db.tablename.help()/db.function.help()–数据库/表单/函数帮助信息
2.1 插入数据
命令模式db.tablename.insert({data}) or db.tablename.save({data})
e.g.
> usermanager_db
>db.user.insert({username:"John Liu", password: "iloveyou"})
>db.user.save({username:"John Nash", password: "John123"})
2.2 删除数据
命令模式db.tablename.remove({criteria})
删除表中的所有记录
db.tablename.remove()
清除所有的表
db.tablename.drop()
e.g.
> db.user.remove({username:"John Liu"})
>db.user.find()
{"_id" : ObjectId("5253fe5ae4ffe9b4ec265535"),"username" : "John Nash", "pass
ord" :"John123" }
2.3 更新数据
命令模式db.tablename.update({criteria},{$set: {new value}})
.
e.g.
> db.user.update({username:"JohnNash"}, {$set:{password:"123456"}})
> db.user.find()
{ "_id" :ObjectId("5253fe5ae4ffe9b4ec265535"), "password" :"123456", "username" : "John Nash" }
2.4 查找数据
命令模式db.tablename.find({criteria})
.
e.g.
username小与等于长度为8:
>db.user.find({$where:"this.username.length<=8"})
username存在:
> db.user.find({username:{$exists: true}})
2.5 建立索引
命令模式db.tablename.ensureIndex(column)
e.g.
> db.user.ensureIndex({username:1})
> db.use.getIndexes()
[ ]
> db.user.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"ns" :"manager_db.user",
"name" :"_id_"
},
{
"v" : 1,
"key" : {
"username" : 1
},
"ns" :"manager_db.user",
"name" :"username_1"
}
]
2.6删除索引
命令模式db.tablename.dropIndex(column)
e.g.
> db.user.dropIndex({username:1})
{ "nIndexesWas" : 2, "ok" : 1}
> db.user.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"ns" : "manager_db.user",
"name" : "_id_"
}
]
2.7 建立唯一索引
>db.user.ensureIndex({username:1}, {unique:true})
>db.user.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"ns" :"manager_db.user",
"name" :"_id_"
},
{
"v" : 1,
"key" : {
"username" :1
},
"unique" : true,
"ns" :"manager_db.user",
"name" :"username_1"
}
]