2 回答

TA贡献1816条经验 获得超4个赞
如果您不必使用 $group 这将解决您的问题:
db.projects.aggregate([
{$sort:{likes:-1}},
{$limit:1}
]).pretty()
结果是
{
"_id" : ObjectId("5ddee7f63cee7cdf247059db"),
"projectname" : "thechosenone",
"username" : "easy",
"likes" : 30,
"links" : ["ssss"]
}

TA贡献1775条经验 获得超8个赞
试试这个:-
db.collection("projects").aggregate([
{
$group: {
_id: { username: "$username" },
likes: { $max: "$likes" },
projectname: { $push : { $cond: [ { $max: "$likes" }, "$projectname", "" ]}}
}
}
,
{
$project:{
username:"$_id.username",
projectname:{"$reduce": {
"input": "$projectname",
"initialValue": { "$arrayElemAt": ["$projectname", 0] },
"in": { "$cond": [{ "$ne": ["$$this", ""] }, "$$this", "$$value"] }
}},
likes:1
}
}
])
添加回答
举报