请求:Node.js+MongoDB按BlockName合并楼层数据
解决Node.js环境下MongoDB按BlockName聚合楼层数据的问题
我是MongoDB新手,需要在Node.js与MongoDB环境下,将同一集合内的4条数据按BlockName进行聚合:把相同楼栋下不同FloorName的楼层数据整合到Floors数组中,输出指定结构。尝试多种方法未得到正确结果,寻求解决办法。
原始数据结构
[ { BlockName: "B1", FloorName: "F1", Units: [ { UnitName: 104, Location: [ "Hall", "Living" ] } ] }, { BlockName: "B1", FloorName: "F2", Units: [ { UnitName: 104, Location: [ "Hall", "Living" ] } ] }, { BlockName: "B2", FloorName: "F1", Units: [ { UnitName: 104, Location: [ "Hall", "Living" ] } ] }, { BlockName: "B2", FloorName: "F2", Units: [ { UnitName: 104, Location: [ "Hall", "Living" ] } ] } ]
期望输出结构
[ { BlockName: "B1", Floors: [ { FloorName: "F1", Units: [ { UnitName: 104, Location: [ "Hall", "Living" ] } ] }, { FloorName: "F2", Units: [ { UnitName: 104, Location: [ "Hall", "Living" ] } ] } ] }, { BlockName: "B2", Floors: [ { FloorName: "F1", Units: [ { UnitName: 104, Location: [ "Hall", "Living" ] } ] }, { FloorName: "F2", Units: [ { UnitName: 104, Location: [ "Hall", "Living" ] } ] } ] } ]
解决方案
MongoDB聚合管道实现
使用$group阶段按BlockName分组,通过$push将每个文档的FloorName和Units字段组合成对象,存入Floors数组:
db.yourCollectionName.aggregate([ { $group: { _id: "$BlockName", Floors: { $push: { FloorName: "$FloorName", Units: "$Units" } } } }, { $project: { _id: 0, BlockName: "$_id", Floors: 1 } } ])
Node.js中使用原生MongoDB驱动的示例
const { MongoClient } = require('mongodb'); async function aggregateBlocks() { const uri = 'mongodb://localhost:27017'; // 替换为你的MongoDB连接字符串 const client = new MongoClient(uri); try { await client.connect(); const db = client.db('yourDatabaseName'); // 替换为你的数据库名 const collection = db.collection('yourCollectionName'); // 替换为你的集合名 const result = await collection.aggregate([ { $group: { _id: "$BlockName", Floors: { $push: { FloorName: "$FloorName", Units: "$Units" } } } }, { $project: { _id: 0, BlockName: "$_id", Floors: 1 } } ]).toArray(); console.log(JSON.stringify(result, null, 2)); } finally { await client.close(); } } aggregateBlocks().catch(console.error);
Node.js中使用Mongoose的示例
const mongoose = require('mongoose'); // 定义数据模型 const buildingSchema = new mongoose.Schema({ BlockName: String, FloorName: String, Units: [{ UnitName: Number, Location: [String] }] }); const Building = mongoose.model('Building', buildingSchema); async function aggregateBlocks() { await mongoose.connect('mongodb://localhost:27017/yourDatabaseName'); // 替换为你的连接字符串 const result = await Building.aggregate([ { $group: { _id: "$BlockName", Floors: { $push: { FloorName: "$FloorName", Units: "$Units" } } } }, { $project: { _id: 0, BlockName: "$_id", Floors: 1 } } ]); console.log(JSON.stringify(result, null, 2)); await mongoose.disconnect(); } aggregateBlocks().catch(console.error);
内容的提问来源于stack exchange,提问作者Prasanth
相关产品推荐
相关产品推荐

