Reputation: 81
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
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 valuedb.collection.aggregate([
{ $match: { "content.name": "color" } },
{ $unwind: "$content" },
{ $match: { "content.name": "color" } },
{ $unwind: "$content.values" },
{
$group: {
_id: null,
values: { $addToSet: "$content.values.name" }
}
}
])
Upvotes: 5