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

MongoDB查询:根据数组对象类型保留全部元素或仅最后一个元素

MongoDB Query to Filter Array Based on Type Field

Hey there! Let's figure out how to get the exact result you're looking for. The key here is to use MongoDB's aggregation framework to conditionally modify the WholeData array based on the Type values inside it.

Solution Query

Here's the aggregation pipeline that will do the trick:

db.yourCollectionName.aggregate([
  {
    $addFields: {
      WholeData: {
        $cond: {
          if: { $in: ["refund", "$WholeData.Type"] },
          then: "$WholeData",
          else: [{ $last: "$WholeData" }]
        }
      }
    }
  }
])

(Don't forget to replace yourCollectionName with the actual name of your collection!)

How It Works

Let's break down each part of the pipeline to understand what's happening:

  • $addFields: This stage updates the existing WholeData field (or creates it if it doesn't exist) with our modified array.
  • $cond: This is our conditional logic checker:
    • if clause: Using $in, we check if the string "refund" exists in the array of Type values extracted from WholeData. MongoDB automatically converts the array of objects into an array of their Type values when we use $WholeData.Type.
    • then clause: If there's at least one "refund" entry in the array, we keep the entire WholeData array as-is.
    • else clause: If all entries are of type "payment", we use $last to grab the final element from the original array, then wrap it in square brackets to maintain the array format required by your result.

Testing with Your Sample Data

When you run this query against your sample documents:

  1. The first document (all "payment" entries) will have its WholeData array reduced to just the last element (EnteredAmount: 200).
  2. The second document (all "refund" entries) will retain the full WholeData array exactly as it was.

This will give you the exact output you specified!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 10:42:45