MongoDB常用语句

1.只统计记录总数:

复制代码
let result = await CorrectionRecordModel.countDocuments(db);

2.数组遍历,循环体中可以有调用异步函数:

复制代码
            for(let item of result2){
                if(item && Tool.checkNotEmptString(item.auth_id) && (item.status !== 1)){
                    await apiUtil.modifyData(EstateDetailModel, {auth_id: item.auth_id}, {
                        status: 1, 
                    });
                }
            }

3.遍历数组,循环体中不可以调用异步函数:

复制代码
                space_service_labels.forEach(item =>{
                    let name = Tool.getEnumValue(14, item);
                    if(Tool.checkNotEmptString(name)){
                        space_service_labels_names.push(name);
                    }
                });

4.对数组,投影出指定对象组成新数组:

复制代码
let ids = list.map(item => item.id);

5.查询出指定距离内的记录:

复制代码
                    db.location = {
                        $near: {
                            $geometry: currentLocation,
                            $maxDistance: distance1
                        }
                    };

6.对查询出的结果数组,按照指定字段再排序:

复制代码
// 按照每组内的记录数降序排序
                groupedArray.sort((a, b) => b.count - a.count);

7.数据查询条件中对结果进行排序(-1从倒序,1正序):

复制代码
db.sort({ update_time : -1 })

8.聚合语句:

复制代码
        let result = await ApiUserPushModel.aggregate([
            {
                $match: {
                    user_id:,
                    create_time: {
                        $gte: start_time,
                        $lte: end_time
                    },
                }
            },
            {
                $group: {
                    _id: '$batch_number',
                    push_count: { $sum: 1 },
                    push_title: { $first: '$push_title' },
                    commission : { $first: '$commission' },
                    notes : { $first: '$notes' },
                    create_time : { $first: '$create_time' },
                    batch_number : { $first: '$batch_number' },
                    data: { $push: '$$ROOT' },
                    
                }
            },
            {
                $project:{
                    _id:0
                }
            }
            
        ]);
  1. 查询是否存在:

    复制代码
             const exist = await UserModel.exists({
                 user_name: user_name
             });
相关推荐
code_whiter6 小时前
01-MySQL数据库基础
数据库·mysql
Evand J6 小时前
【MATLAB例程】三维RRT+APF路径规划与AOA-TDOA融合定位算法。附代码的下载链接
算法·matlab·路径规划·rrt·tdoa·apf·aoa
weixin_382395236 小时前
本地部署 ERP 选型记录:从 Excel 到轻量系统的这几年
数据库·人工智能·数据挖掘
2401_891409267 小时前
期货量化用得上的几类行情数据:逐笔、Level2、分钟线和五档tick
数据库
海绵宝宝转agent7 小时前
leetCode100算法开源笔记分享
笔记·算法
写后端的胖头鱼7 小时前
时间复杂度 & 空间复杂度
java·数据结构·算法·时间复杂度·空间复杂度
hahaha60167 小时前
黑体轨迹和色温--光源白点
人工智能·嵌入式硬件·算法·计算机视觉
海绵宝宝转agent7 小时前
基于Redis ZSet+AOP+注解实现限流注解算法
数据库·redis·算法
imDwAaY8 小时前
Redis 也能做消息队列?从 Stream 的存储讲到消费确认
数据库·redis·缓存
@Mike@8 小时前
13-数据库学习笔记(查询执行处理模型)
数据库·笔记·学习