Skip to content Skip to sidebar Skip to footer

Mongodb Group All Keys And Values In A Collection By A Certain Field

I have collection like this: id:.. Category:Car Type:BMW id:.. Category:Car Type:Ferrari Color:Red id.. Category:Bikes Type:Mountain Bike id.. Category:Bikes Type:BMX I want to

Solution 1:

You're on the right track there.

When converting the entire object to an array, also save the Category field.

The stages needed:

  • $project to save the Category and convert the object to an array
  • $unwind the array to consider each field separately
  • $match to remove _id, Category and any other fields you don't want grouped from the array
  • $group by Category and k to push the values of each key into an array
  • $group by Category to collect the keys and arrays together
  • $project to convert the array with collected values to an object
  • $addFields to inject the Category into the new object
  • $replaceRoot to promote the new object
db.collection.aggregate([
  {$project: {
      Category: 1,
      fields: {$objectToArray: "$$ROOT"}
  }},
  {$unwind: "$fields"},
  {$match: {"fields.k": {$not: {$in: ["_id","Category"]}} }},
  {$group: {
      _id: {
        Category: "$Category",
        key: "$fields.k"
      },
      value: {$push: "$fields.v"}
  }},
  {$group: {
      _id: "$_id.Category",
      fields: {
        $push: {
          "k": "$_id.key",
          "v": "$value"
        }
      }
  }},
  {$project: {
      fields: {$arrayToObject: "$fields"}
  }},
  {$addFields: {
      "fields.Category": "$_id"
  }},
  {$replaceRoot: { newRoot: "$fields"}}
])

Playground

Post a Comment for "Mongodb Group All Keys And Values In A Collection By A Certain Field"