我有以下数据集,需要按字段A分组,并将唯一值添加到现有或新字段。尝试addtoset,但没有成功。非常感谢您的帮助
数据集
A B C
xyz green blah
xyz amber other blah
xyz red asdasda
cdd green asdasdad
Expected
A B
xyz,[green,amber,red]
cdd,green
.aggregate([
{"$unwind": "$RAG" },
{$group : {_id : {A:"$A",B:"$B"}}},testRag: { $addToSet: "$B" }]).toArray(function(err, output)
试试这个:
db.testCollection.aggregate([
{
$group: {
_id: "$A",
"B": {
$addToSet: "$B"
}
}
},
{
$project: {
"_id": 0,
"A": "$_id",
"B": "$B"
}
}
]);
输出:
/* 1 */
{
"A" : "cdd",
"B" : [
"green"
]
},
/* 2 */
{
"A" : "xyz",
"B" : [
"green",
"amber",
"red"
]
}