3

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" }
                ]
            }
           
        ]
    },
]
0

1 Answer 1

5
  • $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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.