MongoDB常用脚本汇总-CSDN博客

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

概述

本文汇总记录日常工作中常用的MongoDB查询脚本。

实战

新增

新增集合

db.getSiblingDB("corpus").createCollection('message');

删除

删除一条数据

db.getSiblingDB("cx_user").userAccount.deleteOne({_id: ObjectId('628720aa454b9b0008ca218f')});

批量删除多条数据

db.getSiblingDB("cx_user").userAccount.deleteMany({_id: {$in: [ObjectId('645af98020506e0008f61268'), ObjectId('6467100e3743bf00088c18c9')]}})

删除集合

db.getSiblingDB("cx_user").getCollection("msg").drop();

更新

通过$set唯一更新未指定的新数据

db.getSiblingDB("corpus").getCollection("risk_control").updateOne({_id: new ObjectId("6502be1b36b36e0008e7888e")}, {"$set": {mobile: "189*****725"}})

$set指定查询条件后批量更新

db.getSiblingDB("corpus").getCollection("risk_control").updateMany({'channel': '77'}, {"$set": {'operator': "johnny"}})

指定多个查询条件

db.getSiblingDB("corpus").getCollection("risk_control").updateMany({'channel': '77', 'type': 1}, {"$set": {'operator': "johnny"}})

查询

查询Server版本

db.version();

distinct查询

db.getSiblingDB("medhub").getCollection("case").distinct('finished');
db.getSiblingDB("cx_user").userAccount.distinct('profiles.channel');

查询某集合下某个JSON Array字段满足Array个数大于等于5的数据

db.getSiblingDB("cx_user").userAccount.find({
	'profiles.5': {$exists: true}
});

profiles是一个JSON Array字段
参考stackoverflow-query-for-documents-where-array-size-is-greater-than-1

$in

findOne

sort

Sort exceeded memory limit of 104857600 bytes, but did not opt in to external sorting.

countDocuments

非常常用的方法必须要掌握的入门API。

使用countDocuments查询符合某一个限制条件的集合总数

db.getSiblingDB("medhub").getCollection("report").countDocuments({
	'translatedReports.zh-CN.profileKey': '64abd052b99c8f0008338990'
});

注上面的translatedReports字段是一个大JSON列通过.连字符以类似于JsonPath的方式取JSON里的Key字段。

使用countDocuments查询符合多个限制条件的集合总数

db.getSiblingDB("medhub").getCollection("report").countDocuments({
	'translatedReports.zh-CN.profileKey': '64abd052b99c8f0008338990',
	'isDelete': false
});

使用countDocuments模糊查询符合限制条件的集合总数

db.getSiblingDB("medhub").getCollection("report").countDocuments({
	'translatedReports.zh-CN.conditionReports.key': /::finding/,
});

注使用/关键词字段/表示模糊查询支持中英文字符。后面介绍的$match也支持模糊查询。

MongoDB不是传统的关系型数据库。如果是传统的关系型数据库如MySQL新增业务场景或需求调整则往往需要在应用层PO里新增一个字段对应的数据库也必须新增一个字段。如果应用新增字段后生产环境的数据库未同步新增字段则大概率会出现问题。这也就是我们所熟悉的数据库发布系统。

使用MongoDB则无此担扰。应用发布后触发特定业务逻辑时数据库会自动新增对应的字段。

使用countDocuments查询不存在某字段的数据总数

db.getSiblingDB("medhub").getCollection("case").countDocuments({
	'alias': null,
});

注上述查询表示早期业务里并没有alias字段后面业务才有此字段。等价于

db.getSiblingDB("medhub").getCollection("case").countDocuments({
	'alias': {$exists: 0},
});

aggregate

聚合查询功能非常强大学习门槛稍微有点高。

不带任何限制条件查询某个集合的总数

db.getSiblingDB("sms").sms_history.aggregate([{$count: "total"}]);

aggregate使用$project查询指定字段

db.getSiblingDB("corpus").getCollection("mds_findings").aggregate([
	{$project: {_id: 0, commonName: 1, key:1, }},
]);

注1表示查询某字段0表示不查询某字段_id: 0,默认会查询主键_id字段如果不想查询此字段则需要显式设置为0。

aggregate使用$project查询指定字段并加上$match过滤符合条件的数据

db.getSiblingDB("corpus").getCollection("mds_findings").aggregate([
	{$project: {_id: 0, key:1, minAge: 1, maxAge: 1}},
    {
      $match: {
        minAge: {$lt: 378691200,},
        maxAge: {$gt: 378691200,}
      },
    },
]);

aggregate使用$match过滤符合条件使用$count查询总数

db.getSiblingDB("corpus").getCollection("mds_findings").aggregate([
//  {$project: {_id: 0, commonName: 1, key:1, minAge:1, maxAge:1}},
    {
      $match: {
        minAge: {$lt: 378691200,},
        maxAge: {$gt: 378691200,}
      },
    },
    {$count: "total"}
]);

$count优先级大于同级$project也就是如果两者并列时只会得到符合条件的总数$project不生效并不会给指定的字段。

参考

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: go