Mongodb Group并从文档中获取其他字段

时间:2019-11-27 19:17:06

标签: javascript mongodb

进行更新,以使Mohammad Faisal拥有最佳解决方案。但是,添加新文档后,它会中断!所以我从他的代码中学到了很多,并对其进行了修改,而且效果很好! =)代码始终在底部。

但这就是我说的.. 所以我有这份文件

{"_id":"5ddea2e44eb407059828d740",
"projectname":"wdym",
"username":"easy",
"likes":0,
"link":["ssss"]
}


{"_id":"5ddea2e44eb407059822d740",
"projectname":"thechosenone",
"username":"easy",
"likes":30,
"link":["ssss"]
}

{"_id":"5ddea2e44eb407059828d740",
"projectname":"thanos",
"username":"wiley",
"likes":10,
"link":["ssss"]
}

基本上我想要的是包含最高级别的文档 喜欢它的相关项目名称

例如,输出为

"projectname":"thechosenone",
"username":"easy",
"likes":30
}
,
{
"projectname":"thanos",
"username":"wiley",
"likes":10,
}

我为此提供的代码如下

db
    .collection("projects")
    .aggregate([
      {
        $group: {
          _id: { username: "$username" },
          likes: { $max: "$likes" }
        }
      },
      {
        $project:{projectname:1}
      }
    ])

$ project给我一个奇怪的输出。然而, 没有$ project的输出是正确的。 但是我想设计项目名称,用户和最高赞。感谢您听到我的声音:)

  

解决方法=)

db
    .collection("projects")
    .aggregate([
      {
        $sort: {
          likes: -1
        }
      },
      {
        $group: {
          _id: {
            username: "$username"
          },
          likes: {
            $max: "$likes"
          },
          projectname: {
            $push: "$projectname"
          },
          link: {
            $push: "$link"
          }
        }
      },
      {
        $project: {
          username: "$_id.username",
          projectname: {
            $arrayElemAt: ["$projectname", 0]
          },
          link: {
            $arrayElemAt: ["$link", 0]
          }
        }
      }
    ])
    .toArray()

2 个答案:

答案 0 :(得分:0)

如果您不必使用$ group,这将解决您的问题:

db.projects.aggregate([
  {$sort:{likes:-1}},
  {$limit:1} 
]).pretty()

结果将是

{
  "_id" : ObjectId("5ddee7f63cee7cdf247059db"),
  "projectname" : "thechosenone",
  "username" : "easy",
  "likes" : 30,
  "links" : ["ssss"]
}

答案 1 :(得分:0)

尝试一下:-

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
    }
  }
])