Is there any way to get distinct records with all columns, and at the same time, concat against another column. For example I have Records:
{ _id : 611a20dfcfbd65f2fbc4aad8, name : "John", skill: "sql", birth :"2000-07-01" }
{ _id : 611a20dfcfbd65f2fbc4aadb, name : "David", skill: "java", birth :"1993-06-08" }
{ _id : 611a20dfcfbd65f2fbc4aade, name : "Tom", skill: "C#", birth :"1990-12-15" }
{ _id : 611a20dfcfbd65f2fbc4aae1, name : "John", skill: "js", birth :"2000-07-01" }
{ _id : 611a20dfcfbd65f2fbc4aae4, name : "Tom", skill: "sql", birth :"1990-12-15"}
{ _id : 611a20dfcfbd65f2fbc4aae7, name : "John", skill: "java", birth :"2000-07-01" }
what I expected is(distinct on name
, concat on skill
)
{ name : "John", skill: "sql,js,java", birth :"2000-07-01" }
{ name : "David", skill: "java", birth :"1993-06-08" }
{ name : "Tom", skill: "C#,sql", birth :"1990-12-15" }
I found some useful answers like:
The problem is I can't properly combine them together.
- The
skill
column returnsnull
with below query
db.collection.aggregate([
{ "$group": {
"_id": "$name",
"doc": { "$first": "$$ROOT" },
"skillArray": { "$push": "$skill" },
}},
{ "$replaceRoot": {
"newRoot": "$doc"
}},
{ "$addFields": {
"skill": {
"$reduce": {
"input": "$skillArray",
"initialValue": "",
"in": {
"$cond": {
"if": { "$eq": [ "$$value", "" ] },
"then": "$$this",
"else": {
"$concat": ["$$value", ",", "$$this"]
}
}
}
}
}
}},
{ $sort: { birth: -1 }}
])
- Almost make it, but this query returns nested record on each line(just remove
{ "$replaceRoot": { "newRoot": "$doc" }},
section of above example)
db.collection.aggregate([
{ "$group": {
"_id": "$name",
"doc": { "$first": "$$ROOT" },
"skillArray": { "$push": "$skill" },
}},
{ "$addFields": {
"skill": {
"$reduce": {
"input": "$skillArray",
"initialValue": "",
"in": {
"$cond": {
"if": { "$eq": [ "$$value", "" ] },
"then": "$$this",
"else": {
"$concat": ["$$value", ",", "$$this"]
}
}
}
}
}
}},
{ $sort: { birth: -1 }}
])