假设我的库存数据如下:
[
{"_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"}
]
现在我希望结果是这样的:
{
"gouped": {
"test_001": ["abc", "xyz"],
"test_002": ["abc"]
}
}
我使用$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 } }
])
这给了我这样的结果:
{ "_id" : "001", "grouped" : [
{ "_id" : "001", "name" : "test_001", "value" : "abc" },
{ "_id" : "002", "name" : "test_001", "value" : "abc" },
{ "_id" : "003", "name" : "test_001", "value" : "xyz" }] }
我想,即使我采用上述格式并使用唯一的value
也可以。然后,我可以使用javascript取得最终结果。