This is my database collection:
JavaScript
x
93
93
1
{"productId" : 1,
2
"isVariant": 1,
3
"isComplete" : 1,
4
"variantId" : 1,
5
"attributeSet" : [
6
{
7
"name" : "Capacity",
8
"value" : "500 GB",
9
"id" : 3
10
},
11
{
12
"name" : "Form Factor",
13
"value" : "5 inch",
14
"id" : 4
15
},
16
{
17
"id" : 5,
18
"name" : "Memory Components",
19
"value" : "3D NAND",
20
"isVariation" : 0
21
}
22
]
23
},
24
{"productId" : 2,
25
"isVariant": 1,
26
"isComplete" : 1,
27
"variantId" : 1,
28
"attributeSet" : [
29
{
30
"name" : "Capacity",
31
"value" : "1 TB",
32
"id" : 3
33
},
34
{
35
"name" : "Form Factor",
36
"value" : "5 inch",
37
"id" : 4
38
},
39
{
40
"id" : 5,
41
"name" : "Memory Components",
42
"value" : "3D NAND",
43
"isVariation" : 0
44
}
45
]
46
},
47
{"productId" : 3,
48
"isVariant": 1,
49
"isComplete" : 0,
50
"variantId" : 1,
51
"attributeSet" : [
52
{
53
"name" : "Capacity",
54
"value" : "500 GB",
55
"id" : 3
56
},
57
{
58
"name" : "Form Factor",
59
"value" : "2.5 inch",
60
"id" : 4
61
},
62
{
63
"id" : 5,
64
"name" : "Memory Components",
65
"value" : "3D NAND",
66
"isVariation" : 0
67
}
68
]
69
},
70
{"productId" : 4,
71
"isVariant": 1,
72
"isComplete" : 0,
73
"variantId" : 1,
74
"attributeSet" : [
75
{
76
"name" : "Capacity",
77
"value" : "1 TB",
78
"id" : 3
79
},
80
{
81
"name" : "Form Factor",
82
"value" : "2.5 inch",
83
"id" : 4
84
},
85
{
86
"id" : 5,
87
"name" : "Memory Components",
88
"value" : "3D NAND",
89
"isVariation" : 0
90
}
91
]
92
}
93
Now I want to send the data of only the attribute where isVariation
is not 0. Also I want to send the variant values of each attribute where isComplete =1
. Hence the result should look like this
JavaScript
1
15
15
1
result : [{
2
"id": 3,
3
"name": "Capacity",
4
"value": [
5
"500 GB",
6
"1 TB"
7
]
8
}, {
9
"id": 4,
10
"name": "Form Factor",
11
"value": [
12
"5 inch"
13
]
14
}]
15
The above result does not have value of 2.5 inch as the isComplete
is 0 for this document. Can anyone help me with the query
Advertisement
Answer
$match
isComplete
is 1$project
to show required fields$unwind
deconstructattributeSet
array$match
attributeSet.isVariation
is not 0$group
byattributeSet.id
and get firstname
and get uniquevalue
using$addToSet
JavaScript
1
19
19
1
db.collection.aggregate([
2
{ $match: { isComplete: 1 } },
3
{
4
$project: {
5
_id: 0,
6
attributeSet: 1
7
}
8
},
9
{ $unwind: "$attributeSet" },
10
{ $match: { "attributeSet.isVariation": { $ne: 0 } } },
11
{
12
$group: {
13
_id: "$attributeSet.id",
14
name: { $first: "$attributeSet.name" },
15
value: { $addToSet: "$attributeSet.value" }
16
}
17
}
18
])
19
The $project stage is not required in your query, i have added because this will optimize your query performance.