Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/42.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 搜索最常见的;“数据”;与猫鼬,猫鼬_Node.js_Mongodb_Mongoose_Aggregation Framework - Fatal编程技术网

Node.js 搜索最常见的;“数据”;与猫鼬,猫鼬

Node.js 搜索最常见的;“数据”;与猫鼬,猫鼬,node.js,mongodb,mongoose,aggregation-framework,Node.js,Mongodb,Mongoose,Aggregation Framework,我的结构 User: { name: "One", favoriteWorkouts: [ids of workouts], workouts: [ { name: "My workout 1" },...] } 我想从数据库中获取最受欢迎/最热门的训练列表 db.users.aggregate( { $unwind : "$favorite" }, { $group : { _id : "$favorite" , number : { $sum : 1 } }

我的结构

User: 
{
  name: "One",
  favoriteWorkouts: [ids of workouts],
  workouts: [ { name: "My workout 1" },...]
}
我想从数据库中获取最受欢迎/最热门的训练列表

db.users.aggregate(
    { $unwind : "$favorite" },
    { $group : { _id : "$favorite" , number : { $sum : 1 } } },
    { $sort : { number : -1 } }
)
这是回报

{
    "hot": [
    {
       "_id": "521f6c27145c5d515f000006",
       "number": 1
    },
    {
       "_id": "521f6c2f145c5d515f000007",
       "number": 1
    },...
]}
但是我想要

{
   hot: [
   {object of hottest workout 1, object of hottest workout 2,...}
]}

如何对最热门的数据进行排序并用对象(而不仅仅是ID)填充结果?

使用MongoDB的聚合框架是正确的。如果使用正确,聚合将为您提供所需的输出。如果您只想查找所有用户最喜爱的训练的_id列表,那么我相信您需要在管道中添加一个额外的$group操作:

db.users.aggregate(
    { $unwind : "$favoriteWorkouts" },
    { $group : { _id : "$favoriteWorkouts", number : { $sum : 1 } } },
    { $sort : { number : -1 } },
    { $group : { _id : "oneDocumentWithWorkoutArray", hot : { $push : "$_id" } } }  
)
这将生成一个以下格式的文档,其中按流行程度列出了训练ID:

{
    "_id" : "oneDocumentWithWorkoutArray",
    "hot" : [
        "workout6",
        "workout1",
        "workout5",
        "workout4",
        "workout3",
        "workout2"
    ]
}

映射到存储在
收藏夹训练
数组中的
\u id
的数据在哪里?MongoDB中没有连接,因此您可能需要将其作为第二步。