MONGO常用操作指令
最佳答案 问答题库718位专家为你答疑解惑
配置:
// 结果50行为1批展示
DBQuery.shellBatchSize = 50
创建:
// 创建表
db.createCollection('table_name')
// 创建索引(unique可选 是否唯一索引)
db.getCollection("table_name").createIndex({column1: 1, column2: 1},{unique: true});
查询:
基础查询
find语法
db.collection.find(query, projection)
query 为可选项,设置查询操作符指定查询条件;
projection 也为可选项,表示使用投影操作符指定返回的字段,如果忽略此选项则返回所有字段。
示例
// 单条件查询
db.getCollection("table_name").find({"_id" : ObjectId("626003cb3eecaa000aac4a22")}).limit(1000).skip(0).pretty()
// 多条件查询
db.getCollection("table_name").find({"_id" : ObjectId("626003cb3eecaa000aac4a22"), "column" : "value"}).limit(1000).skip(0).pretty()
// 指定返回查询
db.getCollection("table_name").find({"column" : "value"}, { _id: 1, column: 1}).limit(1000).skip(0).pretty()
// 条件操作符查询
// 常用操作符: $gt,$lt,$gte,$lte,$ne,$in,$regex,$or,$size
db.getCollection("table_name").find({_id: {$in: [ObjectId("61adde77c1b7d15c5b2ca823"), ObjectId("61add448c1b7d15c5b2ca7f5")]}})
// 查询结果排序(1 是升序,-1 是降序)
db.getCollection("table_name").find({}, {create_time: 1}).sort({"create_time":1}).limit(1000).skip(0).pretty()
聚合查询
aggregate语法
db.aggregate( [ <pipeline> ], { <options> } )
管道操作符
[]
,null
,以及无指定字段 的数据会丢失,若不想丢失参考下方示例)$sort将结果进行排序后输出$limit限制管道输出的结果个数$skip跳过制定数量的结果,并且返回剩下的结果$lookup多表关联查询
// 会丢失[],null,以及无指定字段 的数据
db.getCollection('table_name').aggregate([{$unwind: '$list'}
])// 不会丢失[],null,以及无指定字段 的数据
db.getCollection('table_name').aggregate([{$unwind: {path: '$list', // path是指定字段preserveNullAndEmptyArrays: true //该属性为true即保留}}
])
表达式操作符
示例
// group
db.getCollection("table_name").aggregate([{"$group": {_id:"$create_name"}}])// where + group
db.getCollection("table_name").aggregate([{"$match": {create_name: "zhangsan"}}, {"$group": {_id:"$create_name"}}])// where + group + having
db.getCollection("table_name").aggregate([{"$match": {create_name: "zhangsan"}}, {"$group": {_id:"$create_name", count:{$sum:1}}}, {"$match": {count:{$gt:1}}}])// 多个字段group
db.getCollection("table_name").aggregate([{"$match": {create_time:{$gte:ISODate("2023-09-14T16:00:00.000Z")}}, {"$group": {_id:{create_name: "$create_name", create_time: "$create_time"}, count:{$sum:1}}}])// sum字段
db.getCollection("table_name").aggregate([{"$match": {create_time:{$gte:ISODate("2023-09-14T16:00:00.000Z")}}, {"$group": {_id:{create_name: "$create_name", create_time: "$create_time"}, count:{$sum:"$price"}}}])// Date字段拆分
db.getCollection("table_name").aggregate([{"$match": {create_time:{$gte:ISODate("2023-08-10T16:00:00.000Z")}}}, {"$group": {_id: {create_time: {month: { $month: "$create_time" },day: { $dayOfMonth: "$create_time" },year: { $year: "$create_time"}}}, count:{$sum: 1}}}])// push
db.getCollection("table_name").aggregate([{$group: {_id: '$price',title: { $push: '$title' }}}
])// unwind + project + toLower + toUpper + concat + substr + substrCP + 加减乘除模
db.getCollection("table_name").aggregate([{ $unwind: '$数组列名' },{ $project: {_id: 0,Title: '$title',tags: '$tags',New_Title: { $toLower: '$title'},New_Tags: { $toUpper: '$tags'},Title_Tags: { $concat: ['$title','-','$tags']},Title_Prefix: { $substr: ['$title',0,3]},Title_Prefix_CN: { $substrCP: ['$title',0,6]},Add_Price: { $add: ['$price',1]},Sub_Price: { $subtract: ['$price',1]},Mul_Price: { $multiply: ['$price',2]},Div_Price: { $divide: ['$price',2]},Mod_Price: { $mod: ['$price',2]}}}
])// lookup
db.getCollection("source_table_name").aggregate([{$lookup:{from: "dest_table_name",localField: "source_table_name key",foreignField: "dest_table_name key",as: "new column name"}}
])
options
explain
布尔值 可选的。指定返回有关管道处理的信息。有关示例,请参阅 有关聚合管道操作的返回信息。
在多文档交易中不可用。
allowDiskUse布尔值可选的。允许写入临时文件。设置为时 true
,大多数聚合操作可以将数据写入_tmp
目录中的 dbPath子目录,但以下情况除外:
- $graphLookup 阶段
- $addToSet该$group阶段中使用的累加器表达式 (从4.2.3、4.0.14、3.6.17版开始)
- $push该$group阶段中使用的累加器表达式 (从4.2.3、4.0.14、3.6.17版开始)
从MongoDB 4.2开始,事件探查器日志消息和诊断日志消息包括一个usedDisk
指示符,指示是否有任何聚合阶段由于内存限制而将数据写入临时文件。
cursor
文献可选的。指定游标的初始批处理大小。该cursor
字段的值是带有该字段的文档batchSize
。有关语法和示例,请参见 指定初始批处理大小。maxTimeMS
非负整数 可选的。指定用于游标的处理操作的时间限制(以毫秒为单位)。如果未为maxTimeMS指定值,则操作不会超时。值0
明确指定默认的无限制行为。
MongoDB使用与相同的机制终止超出其分配的时间限制的操作db.killOp()。MongoDB仅在其指定的中断点之一处终止操作。
bypassDocumentValidation
布尔值 可选的。仅当您指定$out或$merge聚合阶段时适用。
允许db.collection.aggregate在操作过程中绕过文档验证。这使您可以插入不符合验证要求的文档。
3.2版中的新功能。
readConcern
文献 可选的。指定读取关注。
从MongoDB 3.6开始,readConcern选项具有以下语法: readConcern: { level: <value> }
可能的阅读关注级别为:
- "local"。当与因果一致的会话相关联时,这是针对主要对象的读取操作和针对次要对象的读取操作的默认读取关注级别。
- "available"。当不与因果关系一致的会话关联时,这是针对次要对象的读取的默认设置。该查询返回实例的最新数据。
- "majority"。可用于使用WiredTiger存储引擎的副本集 。
- "linearizable"。仅可用于读取操作 primary。
有关阅读关注级别的更多信息,请参阅 阅读关注级别。
从MongoDB 4.2开始,此$out阶段不能与“关注”一起使用"linearizable"。也就是说,如果您为指定了"linearizable"读取关注 db.collection.aggregate(),则不能将$out阶段包括 在管道中。
该$merge阶段不能与已关注的内容一起使用"linearizable"。也就是说,如果您为指定了 "linearizable"读取关注 db.collection.aggregate(),则不能将$merge阶段包括 在管道中。
collation
文献 可选的。
指定 用于操作的排序规则。
归类允许用户为字符串比较指定特定于语言的规则,例如字母大写和重音符号的规则。
排序规则选项具有以下语法:
collation: {locale: <string>,caseLevel: <boolean>,caseFirst: <string>,strength: <int>,numericOrdering: <boolean>,alternate: <string>,maxVariable: <string>,backwards: <boolean> }
指定排序规则时,该locale
字段为必填字段;所有其他排序规则字段都是可选的。有关字段的说明,请参见整理文档。
如果未指定排序规则,但是集合具有默认排序规则(请参阅参考资料db.createCollection()),则该操作将使用为集合指定的排序规则。
如果没有为集合或操作指定排序规则,则MongoDB使用先前版本中使用的简单二进制比较进行字符串比较。
您不能为一个操作指定多个排序规则。例如,您不能为每个字段指定不同的排序规则,或者如果对排序执行查找,则不能对查找使用一种排序规则,而对排序使用另一种排序规则。
3.4版的新功能。
hint
字符串或文件 可选的。用于聚合的索引。索引位于运行聚合的初始集合/视图上。
通过索引名称或索引规范文档指定索引。
注意
该hint
不适$lookup和 $graphLookup阶段。
3.6版的新功能。
comment
串 可选的。用户可以指定任意字符串,以帮助通过数据库概要分析器,currentOp和日志来跟踪操作。
3.6版的新功能。
writeConcern
文献 可选的。表示 与or 阶段一起使用的写关注点的文档。$out$merge
忽略对$outor $merge阶段使用默认的写关注。
db.getCollection('table_name').aggregate([{$group: {_id: "$ds",count: { $sum: 1 }}}],{explain: "executionStats"} )
db.getCollection('table_name').explain("executionStats").aggregate([{$group: {_id: "$ds",count: { $sum: 1 }}}])
修改:
更新语法
// 已不推荐使用
db.collection.update(filter, update, options)
// 是对update的封装,不支持{multi:true}属性,加了也没用
db.collection.updateOne(filter,update,options) // Added in MongoDB 4.2
// 是对update的封装,自动加入了 {multi:true}属性,设为false也不行
db.collection.updateMany(filter,update,options) // Added in MongoDB 4.2
更新方法模板
db.collection.update(<filter>,<update>,{upsert: <boolean>, // 默认falsemulti: <boolean>, // 默认falsewriteConcern: <document>,collation: <document>,arrayFilters: [ <filterdocument1>, ... ],hint: <document|string>, // Added in MongoDB 4.2let: <document> // Added in MongoDB 5.0}
)writeConcern:可选,MongoDB写入安全机制,用于控制写入安全的级别。它指定了在写操作完成之前,MongoDB需要接收到的确认数。writeConcern级别越高,写操作的确认就越安全,但也会影响写的性能。writeConcern有三种级别,分别是:
- 1:表示写操作需要写入主节点的内存中,但不需要确认写操作是否成功。这是默认级别。
- majority:表示写操作需要写入大多数节点的内存中,并且需要确认写操作是否成功。
- <number>:表示写操作需要写入指定数量的节点的内存中,并且需要确认写操作是否成功。
如果有需求可以查看文档:https://www.mongodb.com/docs/v5.0/reference/write-concern/
字段更新操作符:
对修改现有文档的更新操作没有影响。
数组字段更新操作符:
更新操作符修饰符
update示例:MongoDB update 彻底聊明白(案例篇) - 知乎
执行返回:WriteResult
执行完update命令之后我们应该明白MongoDB返回的信息,告诉我们成功与否以及更新了多少条等信息;db.collection.update () 方法返回一个WriteResult()对象,其中包含操作的状态。
执行成功
如果执行成功,WriteResult()对象将包含:
- nMatched:匹配查询条件的文档数量
- nUpserted:更新插入的文档数量
- nModified:修改的文档数量
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
执行失败
如果执行失败,WriteResult对象除了成功哪些字段之外,还包含writeConcernError,比较重要的信息有错误信息(errmsg).如下显示写入复制节点超时:
WriteResult({"nMatched" : 1,"nUpserted" : 0,"nModified" : 1,"writeConcernError": {"code" : 64,"errmsg" : "waiting for replication timed out","errInfo" : {"wtimeout" : true,"writeConcern" : {"w" : "majority","wtimeout" : 100,"provenance" : "getLastErrorDefaults"}}
})
示例:
// set更新数据
db.getCollection("table_name").update({"_id" : ObjectId("628cbae13b7750c6711d09f4")}, {$set:{"column":"value"}}, false, true)
// unset去除数据
db.getCollection("table_name").update({"_id" : ObjectId("628cbae13b7750c6711d09f4")}, {$unset:{"column":"value"}}, {upsert:true, multi:true})
// push添加数据
db.getCollection("table_name").update({"_id" : ObjectId("628cbae13b7750c6711d09f4")}, {"$push":{"actions" : "appeal-rule-link"}}, {"$push":{"consumers" : {"source" : "zp_serv13_appeal_audit","timeOut" : NumberInt("1000")}}})
// pull移除数据
db.getCollection("table_name").update({"_id" : ObjectId("628cbae13b7750c6711d09f4")}, {"$pull":{"actions" : ["appeal_check_dispose"]}})
删除:
// 指定query删除
db.getCollection("table_name").remove({create_time:{$gte:ISODate("2023-08-29T01:55:38.000Z"),$lte:ISODate("2023-08-29T01:56:37.999Z")}})
批量操作
// String转Int
db.getCollection('table_name').find({column:{$type:"string"}}).forEach(function(item){ item.column=NumberInt(item.column);db.getCollection('table_name').save(item);}
)// ..._...转...-...
db.getCollection('table_name').find({column:{$regex:"-"}}).forEach(function(item){ item.column = item.column.replace('_', '-');db.getCollection('table_name').update({"_id":item._id},{"$set":{"column":item.column}});}
)// ...aaa...转...bb...
db.getCollection('table_name').find({'column':{'$regex': /aaa/ }}).forEach(function(item) {var tmp = String(item.column)tmp = tmp.replace('aaa','bb')if (tmp == null){print(item.column) }item.column = tmp ;db.table_name.save(item);
});
db.getCollection('table_name').updateMany({'column':{'$regex': "aaa"}},{$set: {column: {$replaceOne: { input:"$column", find:"aaa", replacement:"bb" }}}}
);
其他:
// 计数
db.getCollection("table_name").count()// mongo数据导入导出
1.导出 ./bin/mongoexport -h 'host' -p 'port' --username 'username' --password 'password' -d 'database_name' -c 'collection_name' --authenticationDatabase 'auth' -o dump.txt
2.压缩 tar -zcf dump.tar.gz dump.txt
3.下载 downloadfile dump.tar.gz
4.导入 ./bin/mongoimport -h 'host' -p 'port' --username 'username' --password 'password' -d 'database_name' -c 'collection_name' --authenticationDatabase 'auth' /../dump.txt
99%的人还看了
相似问题
- django ModelSerializer自定义显示字段
- 替换sql,某个字段特定容
- Java之反射获取和赋值字段
- java mybatisplus generator 修改字段类型
- 使用用户代理字段进行浏览器检测(判断页面运行环境)
- js数组操作——对象数组根据某个相同的字段分组
- spring boot加mybatis puls实现,在新增/修改时,对某些字段进行处理,使用的@TableField()
- 【IDEA 使用easyAPI、easyYapi、Apifox helper等插件时,导出接口文档缺少代码字段注释的相关内容、校验规则的解决方法】
- mysql取出组内按照某时间最新一条数据的其他字段
- 基于geotools24.0的创建自动增长主键id字段的方法
猜你感兴趣
版权申明
本文"MONGO常用操作指令":http://eshow365.cn/6-17568-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!