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
WholeDatafield (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 ofTypevalues extracted fromWholeData. MongoDB automatically converts the array of objects into an array of theirTypevalues when we use$WholeData.Type. - then clause: If there's at least one
"refund"entry in the array, we keep the entireWholeDataarray as-is. - else clause: If all entries are of type
"payment", we use$lastto grab the final element from the original array, then wrap it in square brackets to maintain the array format required by your result.
- if clause: Using
Testing with Your Sample Data
When you run this query against your sample documents:
- The first document (all
"payment"entries) will have itsWholeDataarray reduced to just the last element (EnteredAmount: 200). - The second document (all
"refund"entries) will retain the fullWholeDataarray exactly as it was.
This will give you the exact output you specified!
内容的提问来源于stack exchange,提问作者Faizan Ahmed
相关产品推荐
相关产品推荐

