我有一个 Mongo 集合
customer
,其结构如下。
现在我正在尝试将
tier
的所有子文档的 tier_and_details
字段的值提取到一个数组中。
{
"_id": ObjectId("5ca4bbcea2dd94ee58162a69"),
"username": "valenciajennifer",
"name": "Lindsay Cowan",
"address": "Unit 1047 Box 4089\nDPO AA 57348",
"birthdate": ISODate("1994-02-19T23:46:27Z"),
"email": "[email protected]",
"accounts": [
116508
],
"tier_and_details": {
"c06d340a4bad42c59e3b6665571d2907": {
"tier": "Platinum",
"benefits": [
"dedicated account representative"
],
"active": true,
"id": "c06d340a4bad42c59e3b6665571d2907"
},
"5d6a79083c26402bbef823a55d2f4208": {
"tier": "Bronze",
"benefits": [
"car rental insurance",
"concierge services"
],
"active": true,
"id": "5d6a79083c26402bbef823a55d2f4208"
},
"b754ec2d455143bcb0f0d7bd46de6e06": {
"tier": "Gold",
"benefits": [
"airline lounge access"
],
"active": true,
"id": "b754ec2d455143bcb0f0d7bd46de6e06"
}
}
}
结果应该是这样的
["Platinum","Bronze","Gold"]
如何用Mongo聚合管道实现? 这个问题有点像MongoDB:特定子文档的所有字段的聚合值,而答案中的Map-Reduce框架现已被弃用。
一个选项是:
db.collection.aggregate([
{$project: {data: {$objectToArray: "$tier_and_details"}}},
{$project: {_id: 0, data: "$data.v.tier"}}
])
查看它在 playground 示例中的工作原理
另一种选择是:
db.collection.aggregate([
{$project: {
_id: 0,
data: {$map: {
input: {$objectToArray: "$tier_and_details"},
in: "$$this.v.tier"
}}
}}
])
查看它在 playground 示例中的工作原理