Sanjay Gyawali
Sanjay Gyawali

Reputation: 81

How to get distinct values from nested array?

I need to get all the distinct name of color inside the content from the document whose name is "color",

Match criteria to get distinct content.values.name where content.name = color.

The Expected result:

[red, green, blue,tomato, sky, darkblue]

The example Documents:

[
    {
        content:[
            {
                name:"color",
                values: [ 
                  { name: "red" },
                  { name: "green" },
                  { name: "blue" }
                ]
            },
            {
                name:"extra",
                values: [ 
                  { name: "A" },
                  { name: "B" },
                  { name: "C" }
                ]
            }
        ]
    },
    {
        content:[
            {
                name:"color",
                values: [ 
                  { name: "tomato" },
                  { name: "sky" },
                  { name: "darkblue" }
                ]
            },
            {
                name:"extra",
                values: [ 
                  { name: "AA" },
                  { name: "AB" },
                  { name: "AC" }
                ]
            }
           
        ]
    },
]

Upvotes: 3

Views: 3168

Answers (1)

turivishal
turivishal

Reputation: 36094

  • $match color name property and filter the main document
  • $unwind deconstruct content array
  • $match color name and filter sub-document
  • $unwind deconstruct values array
  • $group by null and get unique name from value
db.collection.aggregate([
  { $match: { "content.name": "color" } },
  { $unwind: "$content" },
  { $match: { "content.name": "color" } },
  { $unwind: "$content.values" },
  {
    $group: {
      _id: null,
      values: { $addToSet: "$content.values.name" }
    }
  }
])

Playground

Upvotes: 5

Related Questions