Suppose I have inventory data as follows:
[
{"_id":"0001","name":"test_001","value":"abc"},
{"_id":"0002","name":"test_001","value":"abc"},
{"_id":"0003","name":"test_001","value":"xyz"},
{"_id":"0004","name":"test_003","value":"abc"}
]
Now I want result to be something like this:
{
"gouped": {
"test_001": ["abc", "xyz"],
"test_002": ["abc"]
}
}
I tried something like this using $lookup
db.inventory.aggregate([
{
$lookup:
{
from: "inventory",
let: { name: "$name", value: "$value" },
pipeline: [
{ $match:
{ $expr:
{ $eq: [ "$name", "$$name" ] }
}
},
{ $project: { grouped: 1, name: 1, value: 1 } }
],
as: "grouped"
}
},
{ $project : { grouped : 1 } }
])
This gave me result something like this:
{ "_id" : "001", "grouped" : [
{ "_id" : "001", "name" : "test_001", "value" : "abc" },
{ "_id" : "002", "name" : "test_001", "value" : "abc" },
{ "_id" : "003", "name" : "test_001", "value" : "xyz" }] }
I guess it will be fine even if I get in the above format with unique value
. I can then achieve final result using javascript.