user16690818
user16690818

Reputation:

MongoDB - $addToSet for an Array?

Structure:

[
 {
  "_id": "12",
  "title": "Vanella Icream",
  "contain":"sugar",
  "details": [
      {
        "flavour": "Vanella"
      },
      {
        "weight": "6KG"
      }
   ]
 },
 {
  "_id": "3",
  "title": "Pretzels",
  "contain":"salt",
  "details": [
      {
        "flavour": "Wheat"
      },
      {
        "weight": "2KG"
      }
   ]
 }
]

Expected Output

details:
{
      "flavour": [
        "Vanella",
        "Wheat",
      ],
      "weight": [
        "6KG",
        "2KG",
      ]
}

More Important: I've to do this without details.flavour or details.weight.

I’ve tried with $addToSet, $filter $group but I’m not getting results like that. anyone please suggest.

Mongo Playground: https://mongoplayground.net/p/SXw3jaRDzLy

Upvotes: 3

Views: 1030

Answers (1)

turivishal
turivishal

Reputation: 36104

  • $project to show required field
  • $unwind deconstruct the details array
  • $objectToArray convert details object to array key-value format
  • $unwind deconstruct the details array
  • $group by details key and construct the array of values
  • $group by null and construct the array of details in key-value format
  • $arrayToObject convert above result from key-value format array of object to an object
db.collection.aggregate([
  {
    $project: {
      _id: 0,
      details: 1
    }
  },
  { $unwind: "$details" },
  {
    $project: {
      details: { $objectToArray: "$details" }
    }
  },
  { $unwind: "$details" },
  {
    $group: {
      _id: "$details.k",
      v: { $addToSet: "$details.v" }
    }
  },
  {
    $group: {
      _id: null,
      details: {
        $push: { k: "$_id", v: "$v" }
      }
    }
  },
  {
    $project: {
      _id: 0,
      details: { $arrayToObject: "$details" }
    }
  }
])

Playground

Upvotes: 2

Related Questions