根据数组中的值查找

Lookup based on value in array

我在猫鼬中有以下模式:

userSchema = new mongoose.Schema({
    name: {
        type: String, 
        required: true
        },
    team: {
        type: Schema.Types.ObjectId, ref: 'Team',required:true
        }
})

teamSchema = new mongoose.Schema({
    name: {
        type: String, 
        required: true
    }

   coaches: []
})

如果用户 ID 在团队方案中的 coaches 字段(字符串数组)中,我想加入这些集合。

加入后,我需要过滤以获取在 coaches 属性.

中具有特定 ID 的用户

因此,这里不适合填充。我尝试使用查找,但找不到正确的方法来执行此操作。 对此有什么想法吗?

你正在使用Mongoosejs,我认为你不需要做很多事情,只要让它们之间的适当关系像

teamSchema = new mongoose.Schema({
    name: {
        type: String, 
        required: true
    }

   coaches: [{ type: Schema.Types.ObjectId, ref: 'User' }] // where User is model name 
})

以及如何使用它们

Team.findOne({ name: 'team1' }).populate('coaches').exec();
// or with find
Team.find().populate('coaches').exec();

参考:https://mongoosejs.com/docs/populate.html

根据评论更新

如果你需要传递查询和投影那么

Team.find().populate({
    path: 'coaches',
    match: { name: 'User1' },
    select: 'name -_id' // only user name, remove _id
  }).exec();

参考:https://mongoosejs.com/docs/populate.html#query-conditions

  • $match coaches 数组中的用户 ID
  • $addFields 编辑 coaches 数组
  • $map 迭代 coaches 数组
  • 的循环
  • $toObjectId将string类型coachesid转换成objectId类型
  • $lookup 与用户合集
let result await Team.aggregate([
  { $match: { coaches: "5a934e000102030405000001" } },
  {
    $addFields: {
      coaches: {
        $map: {
          input: "$coaches",
          in: { $toObjectId: "$$this" }
        }
      }
    }
  },
  {
    $lookup: {
      from: "users", // update to correct users collection name
      localField: "coaches",
      foreignField: "_id",
      as: "coaches"
    }
  }
])

Playground