首页 > 解决方案 > 如何在猫鼬中找到具有相同值的字段?

问题描述

我想找到具有相同 match_id 的匹配项,但我无法使用 mongoose 解决。任何帮助将不胜感激,谢谢。我的 match_id 是 String 类型,我想检查正在创建的重复匹配项。匹配模式:

const MatchSchema = new mongoose.Schema({
  match_id: {
    type: String,
  },
  player1Id: {
    type: String,
  },
  player2Id: {
    type: String,
  },
  player1VideoId: {
    type: String,
    default: "blank",
  },
  player2VideoId: {
    type: String,
    default: "blank",
  },
  player1Score: {
    type: Object,
    default:{'noOne':0}
  },
  player2Score: {
    type: Object,
    default:{'noOne':0}
  },
  isWinner:{
    type:String,
  },
  round:{
    type: Number,
  },
  tournamentCategory:{
    type:String,
  },
  tournamentId:{
    type:ObjectID,
  },
  player1Details: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Contestant",
  },
  player2Details: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Contestant",
  },
});

标签: node.jsmongodbmongoose

解决方案


您应该$group用于基于 对数据进行分组match_id,并选择 count > 1 的字段,如下所示

let x = await Model.aggregate([
    {
        $group:{
            _id : "$match_id",
            result : {$push:"$$ROOT"},
            count: { $sum: 1 }
            }
        },
         { "$match": { "count": { "$gte": 2 } } }  

])

推荐阅读