MongoDB 使用手册

MongoDB

常用命令:

  • show dbs 显示所有的数据库
  • use 数据库名 切换到某一个数据中
  • show collections 显示当前数据库中所有的集合
  • db.集合名.find() 查询当前数据库中某一个集合下所有的数据
  • db.集合名.insert({"键": "值", "键": "值" ...}) 给当前数据库中某一个集合添加数据
  • db.集合名.drop() 删除某一个集合
  • db.dropDatabase() 删除当前数据库
> use zyhtest
switched to db zyhtest
> db.student.insert({"name": "zhangsan", "age": 28})
WriteResult({ "nInserted" : 1 })
> show dbs
local    0.000GB
zyhtest  0.000GB
> show collections
student
> db.student.find()
{ "_id" : ObjectId("5745b8a08dfa492b66e7d397"), "name" : "zhangsan", "age" : 28 }
> db.student.drop()
true
> show dbs
local    0.000GB
> db.student.insert({"name": "zhangsan", "age": 28})
WriteResult({ "nInserted" : 1 })
> show dbs
local    0.000GB
zyhtest  0.000GB
> show collections
student
> db.dropDatabase()
{ "dropped" : "zyhtest", "ok" : 1 }
> show dbs
local    0.000GB

文档插入操作

  1. 文档的数据存储格式为BSON,类似于JSON。MongoDB插入数据时会检验数据中是否有“_id”,如果没有会自动生成。
    shell操作有insert和save两种方法。当插入一条数据有“_id”值,并且现在集合中已经有相同的值,使用insert插入时插入不进去,使用save时,会更新数据。

    > db.student.drop()
    true
    > db.student.insert({"_id": 1, "name":"zhangsan", "age": 28})
    WriteResult({ "nInserted" : 1 })
    > db.student.find()
    { "_id" : 1, "name" : "zhangsan", "age" : 28 }
    > db.student.insert({"_id": 1, "name":"zhangsan", "age": 27})
    WriteResult({
            "nInserted" : 0,
            "writeError" : {
                    "code" : 11000,
                    "errmsg" : "E11000 duplicate key error collection: zyhdb.student index: _id_ dup key: { : 1.0 }"
            }
    })
    > db.student.find()
    { "_id" : 1, "name" : "zhangsan", "age" : 28 }
    > db.student.save({"_id": 1, "name":"zhangsan", "age": 27})
    WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
    > db.student.find()
    { "_id" : 1, "name" : "zhangsan", "age" : 27 }
    
  2. 批量插入

    > db.student.insert([{"_id": 2, "name": "lisi"},{"_id": 3, "name": "wangwu"}, {"_id": 4, "name": "zhaoliu", "age": 28}])
    BulkWriteResult({
    "writeErrors" : [ ],
    "writeConcernErrors" : [ ],
    "nInserted" : 3,
    "nUpserted" : 0,
    "nMatched" : 0,
    "nModified" : 0,
    "nRemoved" : 0,
    "upserted" : [ ]
    })
    > db.student.find()
    { "_id" : 1, "name" : "zhangsan", "age" : 27 }
    { "_id" : 2, "name" : "lisi" }
    { "_id" : 3, "name" : "wangwu" }
    { "_id" : 4, "name" : "zhaoliu", "age" : 28 }
    
  3. 循环插入

    > for(var i=0; i<10; i++){db.fortest.insert({num: i})}
    WriteResult({ "nInserted" : 1 })
    > db.fortest.find()
    { "_id" : ObjectId("57469e80142cea1d9aeabab5"), "num" : 0 }
    { "_id" : ObjectId("57469e80142cea1d9aeabab6"), "num" : 1 }
    { "_id" : ObjectId("57469e80142cea1d9aeabab7"), "num" : 2 }
    { "_id" : ObjectId("57469e80142cea1d9aeabab8"), "num" : 3 }
    { "_id" : ObjectId("57469e80142cea1d9aeabab9"), "num" : 4 }
    { "_id" : ObjectId("57469e80142cea1d9aeababa"), "num" : 5 }
    { "_id" : ObjectId("57469e80142cea1d9aeababb"), "num" : 6 }
    { "_id" : ObjectId("57469e80142cea1d9aeababc"), "num" : 7 }
    { "_id" : ObjectId("57469e80142cea1d9aeababd"), "num" : 8 }
    { "_id" : ObjectId("57469e80142cea1d9aeababe"), "num" : 9 }
    

查询操作

先把student删除,再重新插入数据

> db.student.drop()
true
> db.student.insert([{ "_id" : 1, "name" : "zhangsan", "age": 27, "sex": 1 }, { "_id" : 2, "name" : "lisi", "age": 27 } ,{ "_id" : 3, "name" : "wangwu", "age": 30 }, { "_id" : 4, "name" : "zhaoliu", "age": 28 }, { "_id" : 5, "name" : "qianliu", "age": 33 }, { "_id" : 6, "name" : "sunba", "age": 32 }])
BulkWriteResult({
        "writeErrors" : [ ],
        "writeConcernErrors" : [ ],
        "nInserted" : 6,
        "nUpserted" : 0,
        "nMatched" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]
})
> db.student.find()
{ "_id" : 1, "name" : "zhangsan", "age" : 27 }
{ "_id" : 2, "name" : "lisi", "age" : 27 }
{ "_id" : 3, "name" : "wangwu", "age" : 30 }
{ "_id" : 4, "name" : "zhaoliu", "age" : 28 }
{ "_id" : 5, "name" : "qianliu", "age" : 33 }
{ "_id" : 6, "name" : "sunba", "age" : 32 }

查询指定键

> db.student.find({},{name:1})
{ "_id" : 1, "name" : "zhangsan" }
{ "_id" : 2, "name" : "lisi" }
{ "_id" : 3, "name" : "wangwu" }
{ "_id" : 4, "name" : "zhaoliu" }
{ "_id" : 5, "name" : "qianliu" }
{ "_id" : 6, "name" : "sunba" }
> db.student.find({},{_id:0, age:0})
{ "name" : "zhangsan", "sex" : 1 }
{ "name" : "lisi" }
{ "name" : "wangwu" }
{ "name" : "zhaoliu" }
{ "name" : "qianliu" }
{ "name" : "sunba" }
> db.student.find({},{_id:0, name:1})
{ "name" : "zhangsan" }
{ "name" : "lisi" }
{ "name" : "wangwu" }
{ "name" : "zhaoliu" }
{ "name" : "qianliu" }
{ "name" : "sunba" }

各种查询方式

$lt:<
$lte:<=
$gt:>
$gte:>=
$ne:!=

> db.student.find({age:{$lt:30}})
{ "_id" : 1, "name" : "zhangsan", "age" : 27, "sex" : 1 }
{ "_id" : 2, "name" : "lisi", "age" : 27 }
{ "_id" : 4, "name" : "zhaoliu", "age" : 28 }
> db.student.find({age:{$ne:27}})
{ "_id" : 3, "name" : "wangwu", "age" : 30 }
{ "_id" : 4, "name" : "zhaoliu", "age" : 28 }
{ "_id" : 5, "name" : "qianliu", "age" : 33 }
{ "_id" : 6, "name" : "sunba", "age" : 32 }

$in:包含
$nin:不包含

> db.student.find({age:{$in:[27,28]}})
{ "_id" : 1, "name" : "zhangsan", "age" : 27, "sex" : 1 }
{ "_id" : 2, "name" : "lisi", "age" : 27 }
{ "_id" : 4, "name" : "zhaoliu", "age" : 28 }
> db.student.find({age:{$nin:[27,28]}})
{ "_id" : 3, "name" : "wangwu", "age" : 30 }
{ "_id" : 5, "name" : "qianliu", "age" : 33 }
{ "_id" : 6, "name" : "sunba", "age" : 32 }

$or:或者

> db.student.find({$or:[{age:{$lt:29}}, {name:"sunba"}]})
{ "_id" : 1, "name" : "zhangsan", "age" : 27, "sex" : 1 }
{ "_id" : 2, "name" : "lisi", "age" : 27 }
{ "_id" : 4, "name" : "zhaoliu", "age" : 28 }
{ "_id" : 6, "name" : "sunba", "age" : 32 }

null:空值

> db.student.find({sex: null})
{ "_id" : 2, "name" : "lisi", "age" : 27 }
{ "_id" : 3, "name" : "wangwu", "age" : 30 }
{ "_id" : 4, "name" : "zhaoliu", "age" : 28 }
{ "_id" : 5, "name" : "qianliu", "age" : 33 }
{ "_id" : 6, "name" : "sunba", "age" : 32 }

$type:键是某种类型的
double:1
string:2
...

> db.student.insert({_id:7, name:7, age:70})
WriteResult({ "nInserted" : 1 })
> db.student.find({name: {$type: 2}})
{ "_id" : 1, "name" : "zhangsan", "age" : 27, "sex" : 1 }
{ "_id" : 2, "name" : "lisi", "age" : 27 }
{ "_id" : 3, "name" : "wangwu", "age" : 30 }
{ "_id" : 4, "name" : "zhaoliu", "age" : 28 }
{ "_id" : 5, "name" : "qianliu", "age" : 33 }
{ "_id" : 6, "name" : "sunba", "age" : 32 }
> db.student.find({name: {$type: 1}})
{ "_id" : 7, "name" : 7, "age" : 70 }

正则表达式

> db.student.find({name: /si\b/})
{ "_id" : 2, "name" : "lisi", "age" : 27 }

db.集合名称.findOne({查询条件},{指定键})
查询出符合条件的第一条数据

> db.student.findOne()
{ "_id" : 1, "name" : "zhangsan", "age" : 27, "sex" : 1 }

db.集合名称.find({查询条件},{指定键}).limit(数字)
查询前几条数据

> db.student.find().limit(3)
{ "_id" : 1, "name" : "zhangsan", "age" : 27, "sex" : 1 }
{ "_id" : 2, "name" : "lisi", "age" : 27 }
{ "_id" : 3, "name" : "wangwu", "age" : 30 }

db.集合名称.find({查询条件},{指定键}).skip(数字)
跳过前几条数据

> db.student.find().skip(2)
{ "_id" : 3, "name" : "wangwu", "age" : 30 }
{ "_id" : 4, "name" : "zhaoliu", "age" : 28 }
{ "_id" : 5, "name" : "qianliu", "age" : 33 }
{ "_id" : 6, "name" : "sunba", "age" : 32 }
{ "_id" : 7, "name" : 7, "age" : 70 }

可以使用limit()和skip()实现分页

> db.student.find().skip(0).limit(3)
{ "_id" : 1, "name" : "zhangsan", "age" : 27, "sex" : 1 }
{ "_id" : 2, "name" : "lisi", "age" : 27 }
{ "_id" : 3, "name" : "wangwu", "age" : 30 }
> db.student.find().skip(3).limit(3)
{ "_id" : 4, "name" : "zhaoliu", "age" : 28 }
{ "_id" : 5, "name" : "qianliu", "age" : 33 }
{ "_id" : 6, "name" : "sunba", "age" : 32 }
> db.student.find().skip(6).limit(3)
{ "_id" : 7, "name" : 7, "age" : 70 }

db.集合名称.find().sort({键:数字})
数字为1表示升序,数字为2表示降序

> db.student.find().sort({age:1})
{ "_id" : 1, "name" : "zhangsan", "age" : 27, "sex" : 1 }
{ "_id" : 2, "name" : "lisi", "age" : 27 }
{ "_id" : 4, "name" : "zhaoliu", "age" : 28 }
{ "_id" : 3, "name" : "wangwu", "age" : 30 }
{ "_id" : 6, "name" : "sunba", "age" : 32 }
{ "_id" : 5, "name" : "qianliu", "age" : 33 }
{ "_id" : 7, "name" : 7, "age" : 70 }
> db.student.find().sort({age:1, _id:-1})
{ "_id" : 2, "name" : "lisi", "age" : 27 }
{ "_id" : 1, "name" : "zhangsan", "age" : 27, "sex" : 1 }
{ "_id" : 4, "name" : "zhaoliu", "age" : 28 }
{ "_id" : 3, "name" : "wangwu", "age" : 30 }
{ "_id" : 6, "name" : "sunba", "age" : 32 }
{ "_id" : 5, "name" : "qianliu", "age" : 33 }
{ "_id" : 7, "name" : 7, "age" : 70 }

文档修改操作

db.集合名称.update({query},{update},upsert, multi})
query:过滤条件
update:修改内容
upsert:如果不存在查询条件查出的记录,是否插入一条数据,默认是false
multi:是否只修改查询条件查出的第一条记录,默认是false

> db.student.update({_id:1}, {name:"zhang"})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.student.find()
{ "_id" : 1, "name" : "zhang" }
{ "_id" : 2, "name" : "lisi", "age" : 27 }
{ "_id" : 3, "name" : "wangwu", "age" : 30 }
{ "_id" : 4, "name" : "zhaoliu", "age" : 28 }
{ "_id" : 5, "name" : "qianliu", "age" : 33 }
{ "_id" : 6, "name" : "sunba", "age" : 32 }

把整条数据都修改了,如果修改内容中没有设置age字段,则以前的age也取消了,数据全部修改

局部修改

$set:如果存在键则修改,如果不存在键则添加

> db.student.update({_id: 1},{$set:{name:"zhangsan", age: 26}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.student.find()
{ "_id" : 1, "name" : "zhangsan", "age" : 26 }
{ "_id" : 2, "name" : "lisi", "age" : 27 }
{ "_id" : 3, "name" : "wangwu", "age" : 30 }
{ "_id" : 4, "name" : "zhaoliu", "age" : 28 }
{ "_id" : 5, "name" : "qianliu", "age" : 33 }
{ "_id" : 6, "name" : "sunba", "age" : 32 }

id重复时无法修改

> db.student.update({_id:1},{_id:0, name:"zhangsanzhangsan"})
WriteResult({
"nMatched" : 0,
"nUpserted" : 0,
"nModified" : 0,
"writeError" : {
"code" : 16837,
"errmsg" : "The _id field cannot be changed from {_id: 1.0} to {_id: 0.0}."
}
})
> db.student.find()
{ "_id" : 1, "name" : "zhangsan", "age" : 26 }
{ "_id" : 2, "name" : "lisi", "age" : 27 }
{ "_id" : 3, "name" : "wangwu", "age" : 30 }
{ "_id" : 4, "name" : "zhaoliu", "age" : 28 }
{ "_id" : 5, "name" : "qianliu", "age" : 33 }
{ "_id" : 6, "name" : "sunba", "age" : 32 }

第三个参数默认为false,如果查不到数据false时不执行任何操作,true时往数据库里新插入一条数据

> db.student.update({_id:7},{_id:7, name: "songjiu", age:32})
WriteResult({ "nMatched" : 0, "nUpserted" : 0, "nModified" : 0 })
> db.student.update({_id:7},{_id:7, name: "songjiu"}, true)
WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : 7 })
> db.student.find()
{ "_id" : 1, "name" : "zhangsan", "age" : 26 }
{ "_id" : 2, "name" : "lisi", "age" : 27 }
{ "_id" : 3, "name" : "wangwu", "age" : 30 }
{ "_id" : 4, "name" : "zhaoliu", "age" : 28 }
{ "_id" : 5, "name" : "qianliu", "age" : 33 }
{ "_id" : 6, "name" : "sunba", "age" : 32 }
{ "_id" : 7, "name" : "songjiu", "age" : 32 }

第四个参数默认为false,false时表示只修改查询到的第一条数据,true时表示修改查询到的所有数据

> db.student.update({age:32}, {$set:{age:33}}, false, false)
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.student.find()
{ "_id" : 1, "name" : "zhangsan", "age" : 26 }
{ "_id" : 2, "name" : "lisi", "age" : 27 }
{ "_id" : 3, "name" : "wangwu", "age" : 30 }
{ "_id" : 4, "name" : "zhaoliu", "age" : 28 }
{ "_id" : 5, "name" : "qianliu", "age" : 33 }
{ "_id" : 6, "name" : "sunba", "age" : 33 }
{ "_id" : 7, "name" : "songjiu", "age" : 32 }
> db.student.update({age:33}, {$set:{age:32}}, false, true)
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })
> db.student.find()
{ "_id" : 1, "name" : "zhangsan", "age" : 26 }
{ "_id" : 2, "name" : "lisi", "age" : 27 }
{ "_id" : 3, "name" : "wangwu", "age" : 30 }
{ "_id" : 4, "name" : "zhaoliu", "age" : 28 }
{ "_id" : 5, "name" : "qianliu", "age" : 32 }
{ "_id" : 6, "name" : "sunba", "age" : 32 }
{ "_id" : 7, "name" : "songjiu", "age" : 32 }
> db.student.update({age:32}, {$set:{age:33}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.student.find()
{ "_id" : 1, "name" : "zhangsan", "age" : 26 }
{ "_id" : 2, "name" : "lisi", "age" : 27 }
{ "_id" : 3, "name" : "wangwu", "age" : 30 }
{ "_id" : 4, "name" : "zhaoliu", "age" : 28 }
{ "_id" : 5, "name" : "qianliu", "age" : 33 }
{ "_id" : 6, "name" : "sunba", "age" : 32 }
{ "_id" : 7, "name" : "songjiu", "age" : 32 }

$inc:在原来的基础上加多少

> db.student.update({_id:7}, {$inc:{age:-1}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.student.find()
{ "_id" : 1, "name" : "zhangsan", "age" : 26 }
{ "_id" : 2, "name" : "lisi", "age" : 27 }
{ "_id" : 3, "name" : "wangwu", "age" : 30 }
{ "_id" : 4, "name" : "zhaoliu", "age" : 28 }
{ "_id" : 5, "name" : "qianliu", "age" : 33 }
{ "_id" : 6, "name" : "sunba", "age" : 32 }
{ "_id" : 7, "name" : "songjiu", "age" : 31 }

$unset:去掉某个键

> db.student.update({_id:7},{$unset:{age:1}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.student.find()
{ "_id" : 1, "name" : "zhangsan", "age" : 26 }
{ "_id" : 2, "name" : "lisi", "age" : 27 }
{ "_id" : 3, "name" : "wangwu", "age" : 30 }
{ "_id" : 4, "name" : "zhaoliu", "age" : 28 }
{ "_id" : 5, "name" : "qianliu", "age" : 33 }
{ "_id" : 6, "name" : "sunba", "age" : 32 }
{ "_id" : 7, "name" : "songjiu" }

针对数组类型的操作

$push:当数据中不存在键时,创建数组类型的键并插入该值;如果存在该键,并且该键是数组类型时,则在此数组类型的数据上追加;如果存在该键,并且该键不是数组类型时,会报错。
$pushAll:批量往数组中追加
$addToSet:数组中有该值时不追加,没有该值时追加

> db.student.update({_id: 7},{$push:{skill:"java"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.student.find()
{ "_id" : 1, "name" : "zhangsan", "age" : 26 }
{ "_id" : 2, "name" : "lisi", "age" : 27 }
{ "_id" : 3, "name" : "wangwu", "age" : 30 }
{ "_id" : 4, "name" : "zhaoliu", "age" : 28 }
{ "_id" : 5, "name" : "qianliu", "age" : 33 }
{ "_id" : 6, "name" : "sunba", "age" : 32 }
{ "_id" : 7, "name" : "songjiu", "skill" : [ "java" ] }
> db.student.update({_id: 7},{$push:{skill:"mongodb"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.student.find()
{ "_id" : 1, "name" : "zhangsan", "age" : 26 }
{ "_id" : 2, "name" : "lisi", "age" : 27 }
{ "_id" : 3, "name" : "wangwu", "age" : 30 }
{ "_id" : 4, "name" : "zhaoliu", "age" : 28 }
{ "_id" : 5, "name" : "qianliu", "age" : 33 }
{ "_id" : 6, "name" : "sunba", "age" : 32 }
{ "_id" : 7, "name" : "songjiu", "skill" : [ "java", "mongodb" ] }
> db.student.update({_id: 7},{$push:{name:"111"}})
WriteResult({
"nMatched" : 0,
"nUpserted" : 0,
"nModified" : 0,
"writeError" : {
"code" : 16837,
"errmsg" : "The field 'name' must be an array but is of type String in document {_id: 7.0}"
}
})
> db.student.update({_id: 7},{$pushAll:{skill:["js","C++","java"]}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.student.find()
{ "_id" : 1, "name" : "zhangsan", "age" : 26 }
{ "_id" : 2, "name" : "lisi", "age" : 27 }
{ "_id" : 3, "name" : "wangwu", "age" : 30 }
{ "_id" : 4, "name" : "zhaoliu", "age" : 28 }
{ "_id" : 5, "name" : "qianliu", "age" : 33 }
{ "_id" : 6, "name" : "sunba", "age" : 32 }
{ "_id" : 7, "name" : "songjiu", "skill" : [ "java", "mongodb", "js", "C++", "java" ] }
> db.student.update({_id:7},{$addToSet:{skill:"mongodb"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })
> db.student.find()
{ "_id" : 1, "name" : "zhangsan", "age" : 26 }
{ "_id" : 2, "name" : "lisi", "age" : 27 }
{ "_id" : 3, "name" : "wangwu", "age" : 30 }
{ "_id" : 4, "name" : "zhaoliu", "age" : 28 }
{ "_id" : 5, "name" : "qianliu", "age" : 33 }
{ "_id" : 6, "name" : "sunba", "age" : 32 }
{ "_id" : 7, "name" : "songjiu", "skill" : [ "java", "mongodb", "js", "C++", "java" ] }

$pop:删除数组的第一个或最后一个元素,值为-1时是删除第一个元素,值为1时是删除最后一个元素。
$pull:删除数组中的某一个指定的数值
$pullAll:删除数组中多个指定的数值

> db.student.update({_id:7},{$pop:{skill:1}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.student.find()
{ "_id" : 1, "name" : "zhangsan", "age" : 26 }
{ "_id" : 2, "name" : "lisi", "age" : 27 }
{ "_id" : 3, "name" : "wangwu", "age" : 30 }
{ "_id" : 4, "name" : "zhaoliu", "age" : 28 }
{ "_id" : 5, "name" : "qianliu", "age" : 33 }
{ "_id" : 6, "name" : "sunba", "age" : 32 }
{ "_id" : 7, "name" : "songjiu", "skill" : [ "java", "mongodb", "js", "C++" ] }
> db.student.update({_id:7},{$pop:{skill:-1}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.student.find()
{ "_id" : 1, "name" : "zhangsan", "age" : 26 }
{ "_id" : 2, "name" : "lisi", "age" : 27 }
{ "_id" : 3, "name" : "wangwu", "age" : 30 }
{ "_id" : 4, "name" : "zhaoliu", "age" : 28 }
{ "_id" : 5, "name" : "qianliu", "age" : 33 }
{ "_id" : 6, "name" : "sunba", "age" : 32 }
{ "_id" : 7, "name" : "songjiu", "skill" : [ "mongodb", "js", "C++" ] }
> db.student.update({_id:7},{$pull:{skill:"js"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.student.find()
{ "_id" : 1, "name" : "zhangsan", "age" : 26 }
{ "_id" : 2, "name" : "lisi", "age" : 27 }
{ "_id" : 3, "name" : "wangwu", "age" : 30 }
{ "_id" : 4, "name" : "zhaoliu", "age" : 28 }
{ "_id" : 5, "name" : "qianliu", "age" : 33 }
{ "_id" : 6, "name" : "sunba", "age" : 32 }
{ "_id" : 7, "name" : "songjiu", "skill" : [ "mongodb", "C++" ] }
> db.student.update({_id:7},{$pullAll:{skill:["js"]}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })
> db.student.find()
{ "_id" : 1, "name" : "zhangsan", "age" : 26 }
{ "_id" : 2, "name" : "lisi", "age" : 27 }
{ "_id" : 3, "name" : "wangwu", "age" : 30 }
{ "_id" : 4, "name" : "zhaoliu", "age" : 28 }
{ "_id" : 5, "name" : "qianliu", "age" : 33 }
{ "_id" : 6, "name" : "sunba", "age" : 32 }
{ "_id" : 7, "name" : "songjiu", "skill" : [ "mongodb", "C++" ] }
> db.student.update({_id:7},{$pullAll:{skill:["mongodb","C++"]}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.student.find()
{ "_id" : 1, "name" : "zhangsan", "age" : 26 }
{ "_id" : 2, "name" : "lisi", "age" : 27 }
{ "_id" : 3, "name" : "wangwu", "age" : 30 }
{ "_id" : 4, "name" : "zhaoliu", "age" : 28 }
{ "_id" : 5, "name" : "qianliu", "age" : 33 }
{ "_id" : 6, "name" : "sunba", "age" : 32 }
{ "_id" : 7, "name" : "songjiu", "skill" : [ ] }

用户管理操作

1、修改启动MongoDB时要求用户验证
加参数 --auth 即可。
现在我们把MongoDB服务删除,再重新添加服务

mongod --dbpath "D:\work\MongoDB\data" --logpath "D:\work\MongoDB\log\mongodb.log" --install --serviceName "MongoDB" --auth

2、创建用户,并使用创建的用户登录
打开shell操作界面,默认test数据,再查看所有数据库,发现报错,因为没有用户验证。
使用db.auth("user","pwd")进行用户验证。
user:用户名
pwd:密码

因为数据库中没有用户,所以需要先使用无用户验证的方式启动数据,在admin数据库下新建用户。
db.createUser({user:"", pwd:"", roles:[{role:"", db:""}]})
在当前数据库下创建一个用户
user:用户名
pwd:密码
roles:角色信息
[role:角色名, db:对指定数据库的操作]

> db.createUser({user:"admin", pwd:"admin", roles:[{role:"userAdminAnyDatabase", db:"admin"}]})
Successfully added user: {
"user" : "admin",
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
}
]
}

在使用用户验证的方式启动数据库,在数据库admin中,使用admin登录

\> db.auth("admin","admin")
1

状态1表示验证成功,0表示验证失败

创建用户默认给当前使用的数据下创建用户,
例如:当前使用的数据是admin,在admin数据下新建用户
db.createUser({user:"zyh", pwd:"zyh", roles:[{role:"readWrite", db:"zyhdb"}]})
在admin数据库下使用zyh登录,可读写zyhdb的collection。
当在zyhdb下,无法使用zyh登录,因为用户zyh是在admin数据库下。

3、查看当前数据下的用户
show users 显示当前数据库下所有的用户
使用有用户管理权限的用户登录才能看见,例如使用zyh登录后,执行会报错;使用admin登录后,显示用户

> db.auth("zyh","zyh")
1
> show users
2016-06-01T20:32:30.639+0800 E QUERY [thread1] Error: not authorized on admin to execute command { usersInfo: 1.0 } :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
DB.prototype.getUsers@src/mongo/shell/db.js:1523:1
shellHelper.show@src/mongo/shell/utils.js:743:9
shellHelper@src/mongo/shell/utils.js:650:15
@(shellhelp2):1:1

> db.auth("admin","admin")
1
> show users
{
"_id" : "admin.admin",
"user" : "admin",
"db" : "admin",
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
}
]
}
{
"_id" : "admin.zyh",
"user" : "zyh",
"db" : "admin",
"roles" : [
{
"role" : "readWrite",
"db" : "zyhdb"
}
]
}

还可以使用db.getUsers()查看所有的用户
使用db.getUser("user")查询指定用户的具体信息

4、修改用户信息
db.changeUserPassword("user", "newpwd"),修改密码
user:用户名
newpwd:新的密码

db.updateUser("user", {roles:[{role:"", db:""}]})
修改用户信息

db.grantRolesToUser("user", [{role:"", db:""}])
追加角色

db.revokeRolesFromUser("user", [{role:"", db:""}])
取消角色

5、删除用户
db.dropUser("user") 删除指定用户

db.dropAllUsers() 删除当前数据下所有用户

附:常用内置角色说明
数据库用户角色(每个数据库都有的角色)
read 对non-system集合的读取权限,以及以下system集合的读取权限:system.indexes,system.js,system.namespaces
readWrite 对non-system集合的读写权限,以及system.js上的读写权限

数据库管理角色(每个数据库都包含的数据管理角色)
dbAdmin 完成管理性任务的权限,比如schema相关任务、索引、统计信息收集。不能用于管理用户和角色
dbOwner 管理数据库需要的所有权限。包含(readWrite、dbAdmin、userAdmin角色的权限)
userAdmin 在当前数据库创建和修改角色和用户的权限

集群管理角色
admin数据库包含以下角色用于管理整个系统,而不是只针对单个数据库
clusterAmin 提供集群管理的最大权限。包含了clusterManager、clusterMonitor、hostManager角色的权限
clusterManager 管理和监控集群,可以访问local和config数据库。
clusterMonitor 对集群的读权限
hostManager 管理和健康servers

备份和还原角色
admin数据库包含以下角色用于备份和还原数据
backup 备份权限
restore 还原权限

all-database roles
admin数据提供以下角色,对所有数据库都有效。
readAnyDatabase 提供对所有数据库的读权限
readWriteAnyDatabase 提供对所有数据库的写权限
userAdminAnyDatabase 提供对所有数据库用户的管理权限
dbAdminAnyDatabase 对所有数据库的dbAdmin权限

超级角色
角色 说明
root 拥有最高权限

另外角色也可以自定义设置。

java 操作API

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import org.bson.Document;

import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;

public class MongoZyh {

    public static void main(String[] args) {

        try {
            // 连接到MongoDB服务,ServerAddress()两个参数分别为 服务器地址 和 端口
            ServerAddress serverAddress = new ServerAddress("localhost", 27017);
            List<ServerAddress> addrs = new ArrayList<ServerAddress>();
            addrs.add(serverAddress);

            // 三个参数分别为 用户名 数据库名称 密码
            MongoCredential credential = MongoCredential
                    .createScramSha1Credential("zyh", "admin",
                            "zyh".toCharArray());
            List<MongoCredential> credentials = new ArrayList<MongoCredential>();
            credentials.add(credential);

            // 通过连接认证获取MongoDB连接
            MongoClient mongoClient = new MongoClient(addrs, credentials);

            // 连接到数据库
            MongoDatabase mongoDatabase = mongoClient.getDatabase("zyhdb");

            // 新建集合,执行后会在数据库里新建一个空的集合
            // mongoDatabase.createCollection("student");
            // System.out.println("新建集合成功");

            // 获取集合,并往集合中插入数据
            MongoCollection<Document> mongoCollection = mongoDatabase
                    .getCollection("student");

            // 插入一条数据
            // Document document = new Document();
            // document.append("name", "zhangsan");
            // document.append("age", 28);
            // mongoCollection.insertOne(document);
            // System.out.println("插入一条数据成功");

            // 插入多条数据
            // List<Document> documentList = new ArrayList<Document>();
            // Document document1 = new Document();
            // document1.append("name", "lisi");
            // document1.append("age", 28);
            // document1.append("sex", "男");
            // Document document2 = new Document();
            // document2.append("name", "wangwu");
            // document2.append("age", 31);
            // document2.append("sex", "男");
            // documentList.add(document1);
            // documentList.add(document2);
            // mongoCollection.insertMany(documentList);
            // System.out.println("插入多条数据成功");

            // 查询数据
            // 查询集合中所有的数据
            // FindIterable<Document> findIterable = mongoCollection.find();
            // MongoCursor<Document> mongoCursor = findIterable.iterator();
            // while (mongoCursor.hasNext()) {
            // System.out.println(mongoCursor.next());
            // }

            // 根据条件查询
            // Document query = new Document();
            // query.put("age", new Document("$lt", 30));
            // query.put("sex", "男");
            // query.put("name", query);

            // 正则表达式查询
            // Pattern pattern = Pattern.compile("^zhang");
            // query.put("name", pattern);

            // 排序
            // Document sort = new Document();
            // sort.put("name", -1); // 1是正序,-1是倒序

            // FindIterable<Document> findIterable = mongoCollection.find(query)
            // .sort(sort);
            // MongoCursor<Document> mongoCursor = findIterable.iterator();
            // while (mongoCursor.hasNext()) {
            // Document doc = mongoCursor.next();
            // System.out.print("name:" + doc.get("name") + "...");
            // System.out.print("age:" + doc.get("age") + "...");
            // System.out.println("sex:" + doc.get("sex") + "...");
            // }

            // mongoCollection.findOneAndUpdate(查询条件, 修改内容); // 查询出第一条数据并修改
            // mongoCollection.findOneAndDelete(查询条件); // 查询出第一条数据并删除
            // mongoCollection.findOneAndReplace(查询条件, 替换内容); // 查询出第一条数据并替换

            // 修改数据
            // Document query = new Document();
            // query.put("age", 28);
            // Document update = new Document();
            // Document d = new Document();
            // d.put("birthday", new Date());
            // d.put("name", "zhangsan");
            // update.put("$set", d);
            // mongoCollection.updateOne(query, update); // 修改查询到的第一条数据
            // mongoCollection.updateMany(查询条件, 修改内容);// 修改查询到的所有数据

            // 删除数据
            // Document query = new Document();
            // query.put("age", 28);
            // mongoCollection.deleteOne(query); // 删除查询到的第一条数据
            // mongoCollection.deleteMany(查询条件); // 删除查询到的所有数据

            // mongoCollection.drop(); // 删除集合

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
posted @ 2020-07-26 22:24  朝明  阅读(607)  评论(0编辑  收藏  举报