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

MongoDB聚合中用$addToSet实现字符串索引数组的问题

Solution for MongoDB Aggregation to Get Key-Value Origin Object

Hey there! The problem with your current query is that $addToSet only collects values into a numeric-indexed array, but you need a key-value object where each key maps to an origin field and the corresponding value comes from the document's value field. Let's tweak the aggregation to get exactly what you want:

Correct Aggregation Query

use local;
db.getCollection("test_collection").aggregate(
    [
        { "$match": { "type": { "$in": ["type1"] } } },
        { "$group": {
            "_id": { "country": "$country", "time": "$time" },
            "TOT": { "$sum": "$value" },
            "count": { "$sum": 1.0 },
            // Push key-value pairs instead of raw values
            "originPairs": { "$push": { "k": "$origin", "v": "$value" } }
        } },
        { "$project": {
            "TOT": 1,
            "count": 1,
            // Convert the key-value pair array to a proper object
            "origin": { "$arrayToObject": "$originPairs" }
        } }
    ],
    { "allowDiskUse": false }
);

Breakdown of the Changes:

  1. Adjusted $group Stage: Instead of using $addToSet: "$value", we use $push to build an array of structured key-value objects. Each object has a k (key) set to the document's origin and a v (value) set to the document's value. This gives us an array like [{ "k": "O1", "v": 100 }, { "k": "O2", "v": 200 }].
  2. Added $project Stage: We use MongoDB's $arrayToObject operator to convert that array of key-value pairs into a native object—this gives you the { "O1": 100, "O2": 200 } structure you're targeting.

Expected Output:

{
    "_id" : { "country" : "C1", "time" : "1994" },
    "TOT" : NumberInt(300),
    "count" : 2.0,
    "origin" : { "O1" : NumberInt(100), "O2" : NumberInt(200) }
}

This should match exactly what you're looking for!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 22:27:37