我有这样的数据收集:
> db.LogBuff.find()
{ "_id" : ObjectId("578899d5d2b76f77d083f16c"), "SUBJECT" : "DD", "SYS" : "A" }
{ "_id" : ObjectId("578899d5d2b76f77d083f16d"), "SUBJECT" : "AA", "SYS" : "B" }
{ "_id" : ObjectId("578899d5d2b76f77d083f16e"), "SUBJECT" : "BB", "SYS" : "A" }
{ "_id" : ObjectId("578899d5d2b76f77d083f16f"), "SUBJECT" : "AA", "SYS" : "C" }
{ "_id" : ObjectId("578899d5d2b76f77d083f170"), "SUBJECT" : "BB", "SYS" : "A" }
{ "_id" : ObjectId("578899d5d2b76f77d083f171"), "SUBJECT" : "BB", "SYS" : "A" }
{ "_id" : ObjectId("578899d5d2b76f77d083f172"), "SUBJECT" : "CC", "SYS" : "B" }
我想提取如下输出(使用不同的" SYS"值)
{"SUBJECT" : "AA", "SYS" : ["A","B","C","D"]}
{"SUBJECT" : "BB", "SYS" : ["A","B","C","D"]}
{"SUBJECT" : "CC", "SYS" : ["A","B","C"]}
这是我的代码,我被困在中间,请帮我排序
db.LogBuff.aggregate([{
"$unwind": "$SYS"
}, {
"$group": {
_id: {
"_id": "$SUBJECT"
},
SYST: {
$addToSet: "$SYS"
}
}
}, {
"$unwind": "$SYST"
}, {
"$group": {
_id: {
"SUBJECT": "$_id",
"SYST":"$SYST"
}
}
}])
答案 0 :(得分:3)
只需按_id
和addToSet
SYS值分组:
db.LogBuff.aggregate([
{
"$group": {
_id: {
"_id": "$SUBJECT"
},
SYST: {
$addToSet: "$SYS"
}
}
}
])
无需放松,一个group
可以获得所需的结果。
示例数据的组聚合结果:
{ "_id" : { "_id" : "CC" }, "SYST" : [ "B" ] }
{ "_id" : { "_id" : "BB" }, "SYST" : [ "A" ] }
{ "_id" : { "_id" : "AA" }, "SYST" : [ "C", "B" ] }
{ "_id" : { "_id" : "DD" }, "SYST" : [ "A" ] }