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

如何通过MongoDB聚合操作获取文档中多个节点子字段x的最大值?

How to Find the Maximum Value of x in Nested layouts.nodes Array with MongoDB Aggregation

Got it, let's break down how to solve this. You've got configuration documents structured with a layouts.nodes array—each entry in that array is a node object with an x field, and you need to find the highest x value across all those nodes using MongoDB aggregation. Here's exactly what to do:

First, here's the full aggregation pipeline you can run against your collection (replace yourCollection with your actual collection name):

db.yourCollection.aggregate([
  // Unwind the nested nodes array to process each node as a separate document
  { $unwind: "$layouts.nodes" },
  // Group all documents to calculate the global maximum x value
  {
    $group: {
      _id: null,
      maxX: { $max: "$layouts.nodes.x" }
    }
  },
  // Optional: Clean up the output to hide the default _id field
  {
    $project: {
      _id: 0,
      maxX: 1
    }
  }
])

Let's walk through each stage to understand what's happening:

  • $unwind: This stage deconstructs the layouts.nodes array, creating a new document for every single node in the array. This lets MongoDB access each node's x field individually, which is necessary because you can't directly calculate the max of a nested array's fields without first flattening it.
  • $group: We use _id: null here to group all the unwound documents into one result set. The $max accumulator then scans every $layouts.nodes.x value and picks out the largest one, storing it in the maxX field.
  • $project (optional): This step just tidies up the output by removing the auto-generated _id field, leaving you with a clean result like { "maxX": 42 }.

If you need the maximum x per top-level document

If your collection has multiple configuration documents and you want the highest x value for each individual document (instead of a global max across all documents), adjust the $group stage to group by the top-level document's ID:

db.yourCollection.aggregate([
  { $unwind: "$layouts.nodes" },
  {
    $group: {
      _id: "$_id", // Group by the original document's ID
      maxX: { $max: "$layouts.nodes.x" }
    }
  }
])

This will return a result for each configuration document, showing its unique ID and the maximum x value from its layouts.nodes array.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 21:57:46