MongoDB跨多集合按日期分组查询指定用户的关联文档
方案1:应用层分组实现(推荐,易维护调试)
适合数据量不大的业务场景,逻辑清晰无需编写复杂聚合语句:
const { format } = require('date-fns'); const targetUserId = '你要查询的用户ID'; // 并行查询三类数据,提升查询效率 const [meals, activities, roles] = await Promise.all([ Meal.find({ user: targetUserId }).lean(), Activity.find({ user: targetUserId }).lean(), Role.find({ user: targetUserId }).lean() ]); const dateGroup = {}; const dateFormat = 'dd-MM-yyyy'; // 归集餐食数据 meals.forEach(item => { const dateKey = format(item.createdAt, dateFormat); if (!dateGroup[dateKey]) dateGroup[dateKey] = { date: dateKey, meal: [], activity: [], role: [] }; dateGroup[dateKey].meal.push(item); }); // 归集活动数据 activities.forEach(item => { const dateKey = format(item.createdAt, dateFormat); if (!dateGroup[dateKey]) dateGroup[dateKey] = { date: dateKey, meal: [], activity: [], role: [] }; dateGroup[dateKey].activity.push(item); }); // 归集角色数据 roles.forEach(item => { const dateKey = format(item.createdAt, dateFormat); if (!dateGroup[dateKey]) dateGroup[dateKey] = { date: dateKey, meal: [], activity: [], role: [] }; dateGroup[dateKey].role.push(item); }); // 转换为要求的数组格式,可根据需要调整排序逻辑 const history = Object.values(dateGroup).sort((a, b) => new Date(b.date) - new Date(a.date));
方案2:MongoDB聚合查询实现
适合数据量较大、希望直接在数据库层完成聚合的场景,要求MongoDB版本≥4.4(支持$unionWith操作符):
const mongoose = require('mongoose'); const targetUserId = '你要查询的用户ID'; const history = await Meal.aggregate([ // 匹配目标用户的餐食数据 { $match: { user: mongoose.Types.ObjectId(targetUserId) } }, // 标记数据类型 { $addFields: { dataType: 'meal' } }, // 合并活动集合的对应用户数据 { $unionWith: { coll: 'activities', pipeline: [ { $match: { user: mongoose.Types.ObjectId(targetUserId) } }, { $addFields: { dataType: 'activity' } } ] } }, // 合并角色集合的对应用户数据 { $unionWith: { coll: 'roles', pipeline: [ { $match: { user: mongoose.Types.ObjectId(targetUserId) } }, { $addFields: { dataType: 'role' } } ] } }, // 格式化日期为指定格式作为分组key { $addFields: { dateKey: { $dateToString: { format: '%d-%m-%Y', date: '$createdAt' } } } }, // 按日期分组,分别归集三类数据 { $group: { _id: '$dateKey', meal: { $push: { $cond: [{ $eq: ['$dataType', 'meal'] }, '$$ROOT', '$$REMOVE'] } }, activity: { $push: { $cond: [{ $eq: ['$dataType', 'activity'] }, '$$ROOT', '$$REMOVE'] } }, role: { $push: { $cond: [{ $eq: ['$dataType', 'role'] }, '$$ROOT', '$$REMOVE'] } } } }, // 调整返回字段符合要求 { $project: { _id: 0, date: '$_id', meal: 1, activity: 1, role: 1 } }, // 可选:按日期倒序排列 { $sort: { date: -1 } } ]);
注意事项
- 所有集合的
user字段建议添加索引,大幅提升查询效率 - 如果MongoDB版本低于4.4不支持
$unionWith,直接使用方案1即可
内容的提问来源于stack exchange,提问作者unhackit
相关产品推荐
相关产品推荐

