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:
- Adjusted $group Stage: Instead of using
$addToSet: "$value", we use$pushto build an array of structured key-value objects. Each object has ak(key) set to the document'soriginand av(value) set to the document'svalue. This gives us an array like[{ "k": "O1", "v": 100 }, { "k": "O2", "v": 200 }]. - Added $project Stage: We use MongoDB's
$arrayToObjectoperator 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
相关产品推荐
相关产品推荐

