前言
使用mongodb的一些操作记录下,大部分验证使用过,少部分是查找未验证,仅供参考。
正文记录
1、查看所有数据库
show dbs
2、切换到数据库 runoob(没有会创建)
use runoob
3、执行删除命令
db.dropDatabase();
4、删除集合
db.collection.drop();
db.getCollection('collection').drop();5、查询库下所有集合
show tables6、system的集合中(用户,索引,版本号查询)
db.system.users.find();
db.system.indexes.find();
db.system.version.find();
7、密码认证,创建用户,更改用户,删除用户
db.auth("admin","123456");
db.createUser({user:"admin",pwd:"123456",roles:[{"role":"userAdminAnyDatabase","db":"admin"},
{
"role" : "readWriteAnyDatabase",
"db" : "admin"
}]});
db.updateUser({user:"admin",pwd:"123456",roles:[{"role":"userAdminAnyDatabase","db":"admin"},{"role":"readWriteAnyDatabase","db":"admin"}]});
db.dropUser("admin");角色字典:
Read:允许用户读取指定数据库 readWrite:允许用户读写指定数据库
dbAdmin:允许用户在指定数据库中执行管理函数,如索引创建、删除,查看统计或访问system.profile
userAdmin:允许用户向system.users集合写入,可以找指定数据库里创建、删除和管理用户
clusterAdmin:只在admin数据库中可用,赋予用户所有分片和复制集相关函数的管理权限。
readAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的读权限
readWriteAnyDatabase:提供所有数据库读写权限:readWrite,列出集群所有数据库:listDatabases
userAdminAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的userAdmin权限
dbAdminAnyDatabase:只在admin数据库中可用,赋予用户所有数据库的dbAdmin权限。
root:只在admin数据库中可用。超级账号,超级权限
8、对于创建的相关用户进行角色授权
授予角色:db.grantRolesToUser( "userName" , [ { role: "<role>", db: "<database>" } ]);
取消角色:db.grantRolesToUser( "userName" , [ { role: "<role>", db: "<database>" } ]);9、创建自定义角色,并对角色进行授权
创建角色并授权:
db.createRole({
role: "testRole",
privileges: [{ resource: { db: "db", collection: "" }, actions: [ "find" ] }],
roles: []
});
添加Privileges给角色:
db.grantPrivilegesToRole("testRole",
[{ resource: { db: "db", collection: "" },actions: [ "update", "insert", "remove" ]}
]);
10、更改角色
db.updateRole("testRole",{ roles:[{ role: "readWrite",db: "db"}]},{ w:"majority" });
11、创建集合
--db.createCollection(name, options) 说明:name: 要创建的集合名称 options: 可选参数, 指定有关内存大小及索引的选项
例:db.createCollection("mycol", { capped : true, autoIndexId : true, size :
6142800, max : 10000 } )options参数说明:
apped :布尔类型(可选),如果为 true,则创建固定集合。固定集合是指有着固定大小的集合,当达到最大值时,它会自动覆盖最早的文档。当该值为 true 时,必须指定 size 参数。
autoIndexId:布尔类型, 3.2 之后不再支持该参数。(可选)如为 true,自动在 _id 字段创建索引。默认为 false。
size:数值类型(可选),为固定集合指定一个最大值,即字节数。如果 capped 为 true,也需要指定该字段。
max:数值类型(可选),指定固定集合中包含文档的最大数量
12、删除集合
--删除集合
db.collection_name.drop();
--如果你想删除整个集合,可以直接调用remove()方法,传递一个空对象{},表示删除集合中的所有文档
db.collection_name.remove({});
--这个方法仅仅适用于系统集合,如果要删除用户定义的集合,需要先调用drop()方法,然后再使用dropCollection()方法
db.runCommand( { drop: "collection_name" } )13、向集合插入文档
db.collection.insert(document);
3.2 版本后:
--向指定集合中插入一条文档数据
db.collection.insertOne();
--向指定集合中插入多条文档数据
db.collection.insertMany();14、更新文档
--只更新第一条记录:
db.collection.update( {"type":1} , { $set : {"field" : "666"}});
--全部更新:
db.collection.update( {"type":1} , { $set : { "field" : "666"} },false,true );
--只添加第一条:
db.collection.update( {"type":1} , { $set : { "field" : "666"} },true,false );
--全部添加进去:
db.collection.update( {"type":1} , { $set : { "field" : "666"} },true,true );
--全部更新($inc :加一个数字):
db.collection.update( {"type":1} , { $inc : { "nofield" : 1} },false,true);
--只更新第一条记录($inc :加一个数字):
db.collection.update( {"type":1} , { $inc : { "nofield" : 1} },false,false);--更改字段名
db.recommendSpeechSkill.updateMany( {}, {$rename:{"funKeyWord":"keyWord"}})--save() 方法通过传入的文档来替换已有文档,_id 主键存在就更新,不存在就插入
db.collection.save(
{
"_id" : ObjectId("66666666"),
"type" : "1",
"description" : "",
)
15、删除文档
db.collection.remove(<query>,{justOne:<boolean>,writeConcern:<document>,collation<document>})
参数说明:query:必选,删除文档的条件;justOne:可选,false为默认值,删除符合条件的所有文档;true则删除符合条件的一条文档;writeConcern:可选,自定义写出错确认级别;collation:可选,指定特定国家语言的删除归类规则
例:db.collection.remove({"type":1});--只会删除一条记录
db.collection.deleteOne({"type":1});--删除掉所有符合条件的document
db.collection.deleteMany({"type":1});16、创建,重建,删除索引
--createIndex用于3.0及以上版本,ensureIndex用于3.0以下版本
--key表示字段名,1表示升序排序,-1表示降序
db.collection.createIndex({"title":1});
参数说明:
background:Boolean类型,建索引过程会阻塞其它数据库操作,background可指定以后台方式创建索引,即增加 "background" 可选参数。 "background" 默认值为false。
unique:Boolean类型,建立的索引是否唯一。指定为true创建唯一索引。默认值为false.
name:string类型,索引的名称。如果未指定,MongoDB的通过连接索引的字段名和排序顺序生成一个索引名称。
dropDups:Boolean类型,3.0+版本已废弃。在建立唯一索引时是否删除重复记录,指定 true 创建唯一索引。默认值为 false.
sparse:Boolean类型,对文档中不存在的字段数据不启用索引;这个参数需要特别注意,如果设置为true的话,在索引字段中不会查询出不包含对应字段的文档.。默认值为 false.
expireAfterSeconds:integer类型,指定一个以秒为单位的数值,完成 TTL设定,设定集合的生存时间。
v:index version类型,索引的版本号。默认的索引版本取决于mongod创建索引时运行的版本。
weights:document类型,索引权重值,数值在 1 到 99,999 之间,表示该索引相对于其他索引字段的得分权重。
default_language:string类型,对于文本索引,该参数决定了停用词及词干和词器的规则的列表。 默认为英语
language_override:string类型,对于文本索引,该参数指定了包含在文档中的字段名,语言覆盖默认的language,默认值为 language.例如:background:true 的选项,让创建工作在后台执行
db.collection.createIndex({"title":1}, {background: true})--在title字段上重建倒序索引
db.collection.reIndex({"title":-1})-- 删除索引
db.col.dropIndex("title")
17、相同库的集合复制
--方式一
db.getCollection('test1').aggregate([{$out: "test1_copy"}])--方式二
db.getCollection('test1').find().forEach((doc) => {
db.getCollection('test1_copy').insert(doc)
})
18、查询语句
(1)会过滤掉 name 中的相同数据
db.collection.distinct("name");(2)普通查询,name为Tom的数据
db.collection.find({"name": "Tom"});(3)age小于25
db.collection.find({age: {$lt: 25}})
-- age小于等于25
db.collection.find({age: {$lte: 25}})
--age大于等于25
db.collection.find({age: {$gte: 25}})
--不等于
db.collection.find({age: {$ne: 25}});(4)模糊查询,类似 like '%Tom%'
db.collection.find({name: /Tom/});
--类似 like 'Tom%'
db.collection.find({name: /^Tom/});
--类似 like '%Tom'
db.collection.find({name: /Tom$/});--也可写成db.collection.find({field:{$regex:'pattern',$options:<options>}});
例如:db.getCollection('test').find({requParam:{ $regex:/2021/,$options:'i'}})
简洁写法:db.getCollection('test').find({requParam:{ $regex:/2021/i}})
options值可以为:
1、i -- 不区分大小写。
2、m -- 对于包含锚点的模式(即^,对于开始, $结束),在每行的开头或结尾处匹配具有多行值的字符串。如果没有此选项,这些锚点将在字符串的开头或结尾处匹配,如果模式不包含锚点或者字符串值没有换行符(例如\n),则该m选项无效
3、s -- 允许点字符(.)匹配所有的字符,包括换行符。
4、x -- 忽视所有空白字符。(5)分页查询,limit是pagesize,skip是pagenum
db.collection.find().limit(10).skip(10)(6)排序:升序,降序
按age升序排序:db.collection.find({}).sort({age:1})
按age降序排序:db.collection.find().sort({age:-1})(7)查询list字段下存在name字段的数据
db.getCollection('test').find({'list.name':{$exists:true}});
db.getCollection('test').find({'list.name':{$exists:1}});
--不存在
db.getCollection('test').find({'list.name':{$exists:false}});
db.getCollection('test').find({'list.name':{$exists:0}});(8)大于小于日期查询
--Date方式
db.getCollection('test').find({"createTime":{$gte:new Date(2000,1,1)},"createTime":{$lte:new Date(2099,12,1)}});
--ISODate方式
db.getCollection('test').find({"createTime":{$gte:ISODate("2000-01-01T00:00:00Z")},"createTime":{$lte:ISODate("2099-01-01T00:00:00Z")}});
db.getCollection('test1').find({"createTime":{$gte:ISODate("2023-08-17 00:00:00.000Z")},"createTime":{$lte:ISODate("2023-08-17 23:00:00.000Z")}});
19、mongo配合js使用
--例如文档中的字段替换
文档:
{
"_id" : ObjectId("650555e86d69aa8b70fd0eed"),
"carType" : 2.0,
"trick" : "http://ssdsd",
"title" : "你好"
}
--替换trick中//为空
db.getCollection('test2').find({"carType":{"$ne":1}}).
forEach(
function(item) {
var tmp = String(item.trick)
if (tmp == null){
print(item.trick)
}
else{
tmp = tmp.replace("//","");
}
item.trick = tmp ;
db.getCollection('test2').save(item);
print("update to " + item.trick)
}
);
20、聚合管道语法
--pipeline: 一组数据聚合阶段,options: 可选,聚合操作的其他参数
db.collection.aggregate(pipeline, {options})--常用的聚合管道操作
$match:筛选条件,类似 WHERE
$project:投影,类似AS和列过滤
$lookup:左外连接,类似LEFT OUTER JOIN
$sort:排序,类似ORDER BY
$group:分组,类似GROUP BY
$skip/$limit:分页
$unwind:展开数组
$graphLookup:图搜索
$facet/$bucket:分面搜索--分组查询
--例如以carCode为test分组,计算最高价格和最低价格
db.getCollection('car').aggregate([{$match:{"carCode":"test"}},{$group:{_id:"$carCode",min_price:{$min:"$price"},max_price:{$max:"$price"}}}])--关联查询:
db.collection.aggregate([{
$lookup: {
from: "<collection to join>",# 同一个数据库下等待被Join的集合
localField: "<field from the input documents>",# 关联表的关联字段
foreignField: "<field from the documents of the from collection>",# 被关联表的关联字段
as: "<output array field>"# 新的字段名称
}
})