I have tree records in mongodb but there could be many more, I'm getting shops by an ID coming from frontend
{
"_id" : ObjectId("6072c2d7ea13fb0338f6cf05"),
"shopId" : "shop1", <- this is mongodb id
"shopItems" : [
{
_id: ...,
itemId: 1, // mongodb id
itemCount: 5,
colorId: colorId1
}
{
_id: ...,
itemId: 2, // mongodb id
itemCount: 3,
colorId: colorId2
}
]
}
{
"_id" : ObjectId("6072c2d7ea13fb0338f6cf05"),
"shopId" : "shop2", <- this is mongodb id
"shopItems" : [
{
_id: ...,
itemId: 2, // mongodb id
itemCount: 5,
colorId: colorId1
}
{
_id: ...,
itemId: 3, // mongodb id
itemCount: 3,
colorId: colorId2
}
]
}
{
"_id" : ObjectId("6072c2d7ea13fb0338f6cf05"),
"shopId" : "shop3", <- this is mongodb id
"shopItems" : [
{
_id: ...,
itemId: 3, // mongodb id
itemCount: 5,
colorId: colorId1
}
{
_id: ...,
itemId: 1, // mongodb id
itemCount: 3,
colorId: colorId1
}
]
}
I need to get 20 records and group them by itemId and colorId, and get counts for every shop. the count of shops can be 1,2,3,....10etc..
this is output I need:
+--------+----------+-------+-------+-------+
| itemId | colorId | shop1 | shop2 | shop3 |
+========+==========+=======+=======+=======+
| 1 | colorId1 | 5 | 0 | 3 |
+--------+----------+-------+-------+-------+
| 2 | colorId2 | 3 | 0 | 0 |
+--------+----------+-------+-------+-------+
| 3 | colorId2 | 0 | 3 | 0 |
+--------+----------+-------+-------+-------+
| 2 | colorId1 | 0 | 5 | 0 |
+--------+----------+-------+-------+-------+
| 3 | colorId1 | 0 | 0 | 5 |
+--------+----------+-------+-------+-------+
my code is:
const stores = await Store.aggregate([
{ $match: query },
{ $project: { shopId: 1, tt: { $slice: [ "$shopItems", 3 ] } } },
])
I need value 0 if item with itemId and colorId don't exist in shop.
Thank you very much!