带数组的Mongodb查找

带数组的Mongodb查找,mongodb,aggregation-framework,Mongodb,Aggregation Framework,我有两个系列第一个是 用户配置文件集合 const userProfileSchema = mongoose.Schema({ phone_number: { type: String, required: false, }, primary_skills: [ { skill_id: { type: mongoose.Schema.Types.ObjectId, ref: 'Skill' },

我有两个系列第一个是

用户配置文件集合

const userProfileSchema = mongoose.Schema({
  
  phone_number: {
    type: String,
    required: false,
  },
  primary_skills: [
    {
      skill_id: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Skill'
      },
      years: Number,
    }
  ]
});
const skillSchema = mongoose.Schema({
  name: {
    type: String,
    required: true,
    unique:true,
  },
});
样本数据

{
  "phone_number":"222",
   "primary_skills":[{skill_id:1,years:12},{skill_id:2,years:13}]
}
[
   {
   id:1,
   name:'php'
   },
  {
   id:2,
   name:'java'
  }
]
primary_skills
中,键
skill_id
与另一个名为skills的集合映射

技能收集

const userProfileSchema = mongoose.Schema({
  
  phone_number: {
    type: String,
    required: false,
  },
  primary_skills: [
    {
      skill_id: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Skill'
      },
      years: Number,
    }
  ]
});
const skillSchema = mongoose.Schema({
  name: {
    type: String,
    required: true,
    unique:true,
  },
});
样本数据

{
  "phone_number":"222",
   "primary_skills":[{skill_id:1,years:12},{skill_id:2,years:13}]
}
[
   {
   id:1,
   name:'php'
   },
  {
   id:2,
   name:'java'
  }
]
我想获取
用户配置文件
集合中的所有值以及相应的
技能
名称

预期产出:

{
 "phone_number":"222",
 "primary_skills":[{
    name:"php",skill_id:1,years:12
 },{
  name:"java",skill_id:2,years:13}
]
}
我找到了一条与我的问题相似的线索,但它与我想要的正好相反

这就是我尝试的问题

profile.aggregate([{
     $lookup:{
        from:'skills',
        localField:'primary_skills.skill_id',
        foreignField:'_id',
        'as':'primary_skills'
      }
   
}])

这可以正常工作,但它不包含
年份

您需要使用
$unwind
$group
执行此操作

  • $unwind
    主要技能
    ,因为它是一个数组,我们需要按顺序查找子文档
  • $lookup
    加入您已经加入的
    基本技能
  • $unwind
    primary\u skills.name
    我们已经存储了连接结果、它的数组,并且我们正在展开to do对象
  • $addFields
    替换我们有对象且只需要名称的字段
    名称
  • $group
    \u id
    创建,因为我们已展开,需要合并所有文档
游乐场:

  {
    $group: {
      _id: "$_id",
      phone_number: {
        $first: "$phone_number"
      },
      primary_skills: {
        $push: "$primary_skills"
      }
    }
  }
])