【问题标题】:$lookup for id inside array of objects$查找对象数组中的id
【发布时间】:2020-09-15 17:20:03
【问题描述】:

我有一些看起来像这样的模型:

const exerciseDetailSchema = new mongoose.Schema(
    {
        Translations: {
            Name: {
                en: { type: String, required: true },
                no: { type: String }
            }
        }
    }
);

const workoutDetailSchema = new mongoose.Schema(
    {
        Sets: {
            Exercises: [ WorkoutExercises ],
            Units: { type: String }
        }
    }
);

const WorkoutSets = new mongoose.Schema({
    Reps: { type: Number },
    Weight: { type: Number }
});

const WorkoutExercises = new mongoose.Schema({
    ExerciseId: { type: String, required: true },
    Sets: [ WorkoutSets ]
});

基本上,锻炼由集合组成,其中包含一些元数据,包括锻炼。这些练习是一个由锻炼集组成的数组。

我正在尝试进行查询,该查询将返回给我的锻炼详细信息,包括锻炼名称,使其看起来像这样:

{
   _id: "5f60dc1069c27c015ede4e3e",
   Sets: {
      Units: 'metric',
      Exercises: [
         {
            _id: "5f60dc1069c27c015ede4e3e",
            ExerciseId: "5f60c3b7f93d8e00a1cdf414",
            ExerciseName: {
               en: "Squat",
               no: "Knebøy"
            },
            Sets: [
               { _id: "5f60dc1069c27c015ede4e3f", Reps: 10 },
               { _id: "5f60dc1069c27c015ede4e40", Reps: 20 }
            ]
         }
      ]
   }
}

这将是一个示例练习,例如:

{
   _id: "5f60c3b7f93d8e00a1cdf414",
   Translations: {
      Name: {
         en: "Squat",
         no: "Knebøy"
      }
   }
}

我尝试过使用 $lookup,如下所示:

const workout = await WorkoutDetail.aggregate([
        {
            $lookup: {
                from: ExerciseDetail.collection.name,
                localField: "Sets.Exercises.ExerciseId",
                foreignField: "_id",
                as: "ExerciseDetail"
            }
        }
]);

但它总是只返回:ExerciseDetail: [] 用于应该“加入”的部分。谁能提供有关如何正确查询此问题的任何帮助?

更新

我在这里的另一个问题中询问了有关对这些数据进行分组的问题,并收到了一个完美的答案。希望它也可以对其他人有所帮助: MongoDB $group (mongo playground)

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    由于Exercises是一个数组,你需要$unwind来展平数组。

    [
      {
        $unwind: "$Sets.Exercises"
      },
      {
        $lookup: {
          from: "exerciseDetailSchema",
          localField: "Sets.Exercises.ExerciseId",
          foreignField: "_id",
          as: "ExerciseDetail"
        }
      }
    ]
    

    注意:要进行重组,您需要使用$group。因为你对lookup有问题,所以我没有显示。

    工作Mongo playground

    【讨论】:

    • 感谢有关 $unwind、mongo 游乐场和 $group 的信息。我已经尝试了一段时间,并且在正确分组方面遇到了一些问题。你有一个正确设置的想法吗?我这里有一个链接:mongoplayground.net/p/GVQo0LoJd_6
    • 我基本上只需要将每个练习详细信息放入 Set 对象中,但找不到合适的设置
    • @RidgeRobinson 很抱歉回复晚了,我想你已经得到了答案。如果有什么可以联系我
    猜你喜欢
    • 2022-01-18
    相关资源
    最近更新 更多