【语法对照系列】Mongo PK Mysql

189 阅读3分钟

以上语句都实际环境跑过,备注是mongo官网的内容

一、库表操作

动作MongoMySQL备注
1建库use testcreate database test创建test库
2查看所有库show dbsshow databases
3查看当前库dbselect database()
4切换数据库use testuse test
5删除库db.dropDatabase()drop test删除test数据库
6建表db.createCollection(name, options)● name: 要创建的集合名称● options: 可选参数, 指定有关内存大小及索引的选项create table name { 各种字段 }db.collection.xx会自动创建集合collection
7表重命名db.collection.renameCollection( "collection1" )ALTER TABLE tablename1RENAME TO tablename2
8查看库里面所有表show collections或者show tablesshow tables
9清空表db.collection.remove({})truncate table collection
10删除表db.collection.drop()drop table collection
11创建普通索引db.collection.createIndex({"key":options})options 1 升序 -1 降序ALTER TABLE table_name ADD INDEX index_name (column_list)Mongo 当系统已有大量数据时,使用后台创建索引db.collection.createIndex({"key":options},{backgroud:true})
12创建组合索引db.collection.createIndex({"key":options,"key2":options})ALTER TABLE table_name ADD INDEX index_name (column_list,column_list)2
13创建唯一索引db.collection.ensureIndex({firstname: 1, lastname: 1}, {unique: true});db.collection.ensureIndex({'pkc': 1},{unique: true,name: 'index_name'});Deprecated since version 3.0: db.collection.ensureIndex() has been replaced by db.collection.createIndex().ALTER TABLE table_name ADD UNIQUE (column_list)
14查看表的索引db.collection.getIndexes()show index from table_name

二、查询

ps:命令行模式在find()方法后直接追加pretty()方法 可以格式化输出

序号动作MongoMysql备注
1普通db.getCollection('collection').find({})select * from tablenamecollection不存在时会自动创建,tablename不存在时会报错
2条件查询anddb.getCollection('collection').find({"name":"梧桐","age":18})select * from tablenamewhere name = "梧桐" and age = 18
3条件查询ordb.getCollection('collection').find({$or:[{'name':'梧桐2'},{'name':'梧桐1'}]})select * from tablename where name = "梧桐1" or name= "梧桐2"
4条件查询>,<, >=,<=db.getCollection('collection').find("age":{$gt:18})select * from tablename where age > 18gt :>gt  : >lt   : <$gte : >=$$lte : <=
ISODatedb.getCollection('tablename').find({'gmtCreate':{gt:ISODate("20191204T00:00:00.000Z"),gt:ISODate("2019-12-04T00:00:00.000Z"),lt:ISODate("2019-12-05T00:00:00.000Z")}})select * from tablename where gmtCreate > "2019-12-04T00:00:00.000"and "2019-12-05T00:00:00.000"
5条件查询 and,or,<db.getCollection('collection').find({or:[{and:[{"name":"梧桐"},{"age":18}]},{"age":{$lt:18}}]})select * from tablename where (name = '梧桐'and sex = '男' )or age < 18$and must be an array
6条件查询!=db.collection.find({"name":{$ne:"梧桐"}})select * from tablename where name != '梧桐'db.getCollection('collection')和db.collection都可以
7条件查询 indb.collection.find({"name":{$in:["梧桐","梧桐雨"]}})select * from tablename where name in ("梧桐","梧桐雨")
8条件查询not indb.collection.find({"name":{$nin:["梧桐","梧桐雨"]}})select * from tablename where name not in ("梧桐","梧桐雨")$nin 这个东西不推荐
9条件查询limitdb.collection.find({}).limit(1)select * from tablename limit 1
10条件查询返回指定字段db.collection.find( {},{ "name": 1, "age": 1 })select name,agefrom tablenamemongo第一个参数为查询条件,空代表查询所有
11条件查询返回除指定字段外其他字段db.collection.find( {},{ "sex": 0 })这个要写存储过程,略
12排序sortdb.getCollection('collecton').find({}).sort({age:1}).limit(1)select * from tablename order by age limit 1Mongo 如果按照 id排序db.getCollection('t_holder').find().sort({"_id":1})
13分页查询skipdb.getCollection('t_asset_event_collect').skip(2).limit(3)select * from tablename limit 2,3
14分组 groupdb.getCollection('t_event_collect').group({key:{ "gmtMirror":true},initial: {count:0},reduce:function(obj,prev){prev.count++;},condition:{"quantity":{$gt:0}}})返回 类和计数select *from tablename group by gmt_mirror having quantity > 0group参数选项:1.key: 这个就是分组的key2.initial: 每组都分享一个初始化函数,特别注意:是每一组initial函数。3.reduce: 这个函数的第一个参数是当前的文档对象,第二个参数是上一次function操作的累计对象。有多少个文档, $reduce就会调用多少次。4.condition: 这个就是过滤条件。5.finalize: 这是个函数,每一组文档执行完后,多会触发此方法。
15分组aggeratedb.getCollection('t_event_collect').aggregate([//如果有条件 match{match :{"device":2,"holder":1}},{ group : {_id : {gmtMirror:"gmtMirror"},object: {first:"$$ROOT"}}},{ $sort :{ gmtMirror :1,quantity:1}}])select * from tablename gr$$ROOT 返回对象first返回第一条first 返回第一条group 分组
16分组aggeratedb.getCollection('t_holder').aggregate([{group:{_id : {agentNo:"agentNo"},count: {sum: 1}}},{sort:{"count":-1}},{$limit:1}])select count(1) as a from t_detail_2 group by holder ORDER BY a desc limit 1;
分组 aggregatedb.getCollection('t_holder').aggregate([{group:{_id : {agentNo:"agentNo",type:"type",code:"type",code:"code"},count: {sum: 1}}},{match:{count:{gt :1},"_id.agentNo":{ne:""}}}])select count(1),agentNo from t_holder ORDER BY agentNo having count(1) >1 and agentNo != ""查询表中的重复数据集
17分组db.collection.aggregate({"group":{_id: 'sex',max:{"max":"$age"}}});select max(age) from tablename group by sexaddToSet](https://docs.mongodb.com/manual/reference/operator/aggregation/addToSet/#grp._S_addToSet) 将符合筛选的字段组合成集合并返回[avg 平均值first](https://docs.mongodb.com/manual/reference/operator/aggregation/first/#grp._S_first) 第一条记录[last 最后一条记录max](https://docs.mongodb.com/manual/reference/operator/aggregation/max/#grp._S_max) 最大值[min 最小值sum](https://docs.mongodb.com/manual/reference/operator/aggregation/sum/#grp._S_sum) 总计[mergeObjects 返回几条记录中 的所有字段,记录该字段最后一条记录的值push](https://docs.mongodb.com/manual/reference/operator/aggregation/push/#grp._S_push)[stdDevPop$stdDevSamp
18聚合函数sumdb.t_event_collect.aggregate([{group: {_id: null,count: { sum: "$quantity" } }}])select sum(quantity) from tablenameIn MongoDB 3.2 and earlier, sum](https://docs.mongodb.com/manual/reference/operator/aggregation/sum/#grp._S_sum) is available in the [group stage only.sum](https://docs.mongodb.com/manual/reference/operator/aggregation/sum/#grp._S_sum) is available in the following stages:● [groupproject](https://docs.mongodb.com/manual/reference/operator/aggregation/project/#pipe._S_project)● [addFields (Available starting in MongoDB 3.4)● set](https://docs.mongodb.com/manual/reference/operator/aggregation/set/#pipe._S_set) (Available starting in MongoDB 4.2)● [replaceRoot (Available starting in MongoDB 3.4)● replaceWith](https://docs.mongodb.com/manual/reference/operator/aggregation/replaceWith/#pipe._S_replaceWith) (Available starting in MongoDB 4.2)● [match stage that includes an $expr expression
19聚合函数sum 加总多个字段db.t_event_collect.aggregate([{group: { _id: null, count: { sum:{multiply:["multiply:["quantity","$holder"]} } }}])select sum(english + yuwen) from tablename;
20聚合函数count写法一:db.t_event_collect.aggregate([{ group: { _id: null, myCount: { sum: 1 } } }])写法二:db.t_event_collect.aggregate([{$count:"quantity"}])select count(1) from tablenamesum:1表示每次符合加1sum: 1 表示每次符合加1sum: 2 表示每次符合加2
21函数max,min,avgdb.t_event_collect.aggregate([{group: { _id: null, count: { max: "$quantity" } }}])select max(quantity) from tablenamemaxmaxmin$avg

三、更新

序号动作MongoMysql
1单/多条更新方法一:db.people.findAndModify({query: { name: "梧桐" },sort: { weight: 1 },update: {inc:weight:1,inc: { weight: 1 },set:{score :99}}})方法二:db.people.update({ name: "Andy" },{inc:weight:1,inc: { weight: 1 },set: {score : "99",// "info.publisher": "2222",// tags: [ "software" ],// "ratings.1": { by: "xyz", rating: 3 }}}//,// { upsert: true })update tablename set weight= weight+ 1,score = 99 where name = "梧桐" order by weight方法一:db.collection.findAndModify({query: ,sort: ,remove: ,update: , // Changed in MongoDB 4.2new: , //new :true 配合 upsert: true 使用,返回新增的记录,false 返回 nullfields: ,upsert: , //upsert: true 没有就新增,bypassDocumentValidation: ,writeConcern: ,collation: ,//New in version 3.4 指定的语言规则arrayFilters: [ , ... ]});arrayFilters是数组筛选,下面语句表示 筛选 grades 含大于等于 100 ,将 其中大于等于100的更新成100db.students.findAndModify({query: { grades: { gte: 100 } },update: { set: { "grades.[element]" : 100 } },arrayFilters: [ { "element": { gte: 100 } } ]})方法二:db.collection.update(,,{upsert: ,multi: ,//多条更新需要 multi: truewriteConcern: ,collation: ,arrayFilters: [ , ... ],hint: <documentstring> // Available starting in MongoDB 4.2})
2批量更新-update tablename case when id = 1 then age = 18 else age = age where id in (1)
3插入db.collection.insert([{"name":"梧桐","age":18},{"name":"梧桐雨","age":17}])insert tablename (name,age) values ("梧桐",18),("梧桐雨",17)db.collection.insert()db.collection.insertOne() New in version 3.2db.collection.insertMany() New in version 3.2

四、删除

序号动作MongoMysql
1删除某些条记录db.t_asset_event_collect.remove({"gmtMirror":{$in:[20190815,20190814,20190813]},"device":3})delete from tablename where gmtMirror in (20190815,20190814,20190813) and device = 2
2删除某些列db.getCollection('collection').update({"class":{exists:true}},{unset:{"class":"","total":""}},{multi:true})ALTER TABLE tablename drop column class,drop column total;Mongo 可以指定条件The $unset operator deletes a particular field.

五、Mongo 特有语法

序号动作Mongo
1查询某字段存在的记录db.getCollection('t_event_update_20200313').find({'tp':{$exists:true}})
2根据字段类型查询数据db.getCollection('t_mq_cache').find({"_id":{$type:"objectId"}})docs.mongodb.com/manual/refe…

六、调优

序号动作MongoMysql
1查看执行过程普通查询:db.t_event_collect.find().explain()分组查询db.t_asset_event_collect.explain().aggregateexplainsql
2强制走某条索引db.collection.find({age:{$lt:18}}).hint({name:1, age:1})select * from tablename FORCE INDEX(idx_name_age) where age < 18