MongoDB常用脚本汇总

概述

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

实战

新增

新增集合:

js 复制代码
db.getSiblingDB("corpus").createCollection('message');

删除

删除一条数据:

js 复制代码
db.getSiblingDB("cx_user").userAccount.deleteOne({_id: ObjectId('628720aa454b9b0008ca218f')});

批量删除多条数据:

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

删除集合:

js 复制代码
db.getSiblingDB("cx_user").getCollection("msg").drop();

更新

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

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

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

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

指定多个查询条件:

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

查询

查询Server版本:

js 复制代码
db.version();

distinct查询:

js 复制代码
db.getSiblingDB("medhub").getCollection("case").distinct('finished');
db.getSiblingDB("cx_user").userAccount.distinct('profiles.channel');

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

js 复制代码
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查询符合某一个限制条件的集合总数:

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

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

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

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

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

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

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

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

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

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

js 复制代码
db.getSiblingDB("medhub").getCollection("case").countDocuments({
	'alias': null,
});

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

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

aggregate

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

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

js 复制代码
db.getSiblingDB("sms").sms_history.aggregate([{$count: "total"}]);

aggregate使用$project查询指定字段:

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

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

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

js 复制代码
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查询总数:

js 复制代码
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不生效,并不会给指定的字段。

参考

相关推荐
坚定信念,勇往无前2 天前
docker安装mongodb
mongodb·docker·容器
云和数据.ChenGuang4 天前
openEuler系统下安装MongoDB的技术教程
运维·数据库·mongodb·压力测试·运维工程师·运维技术
ChristXlx4 天前
Linux安装MongoDB(虚拟机适用)
linux·mongodb·postgresql
2301_796512524 天前
React Native鸿蒙跨平台开发如何使用MongoDB或Firebase作为后端数据库来存储车辆信息、保养记录和预约信息
数据库·mongodb·react native
数据与人5 天前
mongodb报错Sort exceeded memory limit of 104857600 bytes
数据库·mongodb
赵渝强老师5 天前
【赵渝强老师】MongoDB的数据类型
数据库·mongodb·nosql
济南java开发,求内推5 天前
MongoDB: 升级版本至:5.0.28
数据库·mongodb
wusp19946 天前
基于vite + nodejs + MongoDB + vue2 的博客发布系统
数据库·mongodb
这儿有一堆花6 天前
JSON 与 MongoDB:直存对象的便利与隐性代价
数据库·mongodb·json
嫂子的姐夫7 天前
py连接MongoDB
数据库·爬虫·mongodb