You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SpringBoot中如何从MongoDB获取并按Stack/SubStack分类的数组数据

Got it, let's tackle this problem step by step. You want to return your MongoDB documents grouped first by stack, then by subStack, in a nested structure via a REST API. Let's cover two solid approaches—one leveraging MongoDB's aggregation framework (great for large datasets since processing happens in the database) and another handling the grouping in your backend code (flexible if you need extra custom logic).

Approach 1: MongoDB Aggregation Framework

This is the most efficient way because we let the database do the heavy lifting, reducing the amount of data transferred to your backend. Here's the aggregation pipeline you can use:

db.yourCollectionName.aggregate([
  // First group by both stack and subStack to collect all docs for each pair
  {
    $group: {
      _id: { stack: "$stack", subStack: "$subStack" },
      documents: { $push: "$$ROOT" } // Push the entire document into the array
    }
  },
  // Next group by stack to nest subStack groups under their parent stack
  {
    $group: {
      _id: "$_id.stack",
      subStackGroups: {
        $push: {
          k: "$_id.subStack",
          v: "$documents"
        }
      }
    }
  },
  // Convert the grouped data into a clean key-value structure
  {
    $replaceRoot: {
      newRoot: { $arrayToObject: [["$_id"], "$subStackGroups"] }
    }
  }
])

How this works:

  1. First $group: Clusters all documents by their stack and subStack pair, collecting the full documents into an array.
  2. Second $group: Groups those results by stack, creating an array of key-value pairs where each key is a subStack and the value is the corresponding documents array.
  3. $replaceRoot: Converts the grouped data into a top-level object where each key is a stack, and its value is another object mapping subStacks to their document arrays.
Approach 2: Backend Processing (Node.js/Express Example)

If you prefer to handle the grouping in your backend (e.g., if you need to modify documents before grouping), here's how you can do it with Express and Mongoose:

const express = require('express');
const router = express.Router();
const YourModel = require('../models/yourModel'); // Replace with your model path

router.get('/stack-grouped-data', async (req, res) => {
  try {
    // Fetch all documents from MongoDB
    const allDocuments = await YourModel.find({}).lean(); // Use .lean() to get plain JS objects (faster)
    
    // Initialize an empty object to hold our grouped structure
    const groupedResult = {};

    allDocuments.forEach(doc => {
      const { stack, subStack } = doc;

      // Create the stack key if it doesn't exist
      if (!groupedResult[stack]) {
        groupedResult[stack] = {};
      }

      // Create the subStack array if it doesn't exist
      if (!groupedResult[stack][subStack]) {
        groupedResult[stack][subStack] = [];
      }

      // Add the current document to the corresponding subStack array
      groupedResult[stack][subStack].push(doc);
    });

    // Send the grouped structure as JSON response
    res.json(groupedResult);
  } catch (error) {
    res.status(500).json({ error: 'Failed to fetch and group data', details: error.message });
  }
});

module.exports = router;

Expected Valid Output Format

Note: The example format you shared ([ "webTechnology":[ "angular":[ {...} ] ] ]) isn't valid JSON because arrays can't contain key-value pairs. The correct structure (returned by both approaches above) will be a nested object like this:

{
  "webTechnology": {
    "angular": [
      { "stack": "webTechnology", "subStack": "angular" },
      { "stack": "webTechnology", "subStack": "angular" }
    ],
    "react": [
      { "stack": "webTechnology", "subStack": "react" }
    ]
  },
  "script": {
    "python": [
      { "stack": "script", "subStack": "python" }
    ],
    "javaScript": [
      { "stack": "script", "subStack": "javaScript" }
    ]
  },
  "Java": {
    "Spring": [
      { "stack": "Java", "subStack": "Spring" }
    ]
  }
}

内容的提问来源于stack exchange,提问作者Nithyananth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:11:11