Node.js中MongoDB聚合:按地点分组限制每组街道数
解决方案
以下是Node.js中使用MongoDB聚合查询实现需求的代码:
const { MongoClient } = require('mongodb'); async function getLimitedStreets() { const uri = 'mongodb://localhost:27017'; // 替换为你的MongoDB连接字符串 const client = new MongoClient(uri); try { await client.connect(); const db = client.db('your-database-name'); // 替换为你的数据库名 const collection = db.collection('your-collection-name'); // 替换为你的集合名 const pipeline = [ // 展开items数组,将每个子文档转为独立文档 { $unwind: '$items' }, // 按location分组,收集对应的街道列表(保留原始顺序) { $group: { _id: '$items.location', streets: { $push: '$items.street' } } }, // 截取每个location的前2条街道,并重命名字段 { $project: { _id: 0, location: '$_id', street: { $slice: ['$streets', 2] } } }, // 将所有分组结果收集到items数组中 { $group: { _id: null, items: { $push: '$$ROOT' } } }, // 只保留items字段,移除默认的_id { $project: { _id: 0 } } ]; const result = await collection.aggregate(pipeline).toArray(); console.log(JSON.stringify(result[0], null, 2)); return result[0]; } finally { await client.close(); } } getLimitedStreets().catch(console.error);
聚合管道各阶段说明
- $unwind:将原始文档中的
items数组拆分为多个独立文档,每个文档包含原文档的其他字段和一个items子文档(对应数组中的一项),为后续按location分组做准备。 - $group(第一阶段):以
items.location为分组键,用$push将同一location下的所有街道名称收集到streets数组中,$push会保留街道在原数组中的顺序。 - $project:把分组的
_id(即location)重命名为location,同时用$slice截取streets数组的前2个元素,得到每个location最多2条街道的列表。 - $group(第二阶段):以
_id: null做全局分组,将所有处理后的location文档收集到items数组中。 - $project:移除结果中的
_id字段,只保留最终的items数组,与期望输出格式一致。
运行上述代码后,即可得到你需要的输出结构。
内容的提问来源于stack exchange,提问作者bitu
相关产品推荐
相关产品推荐

