获取模型中的额外字段,汇总查找文档中的所有记录

Get extra field in model summing all records from lookup document

有这个模型:

const matchSchema = mongoose.Schema({
    location: {type: mongoose.Types.ObjectId, ref: 'Location'},
    datetime: Date,
    teamAName: String,
    teamBName: String,
    teamA: [{type: mongoose.Types.ObjectId, ref: 'Player'}],
    teamB: [{type: mongoose.Types.ObjectId, ref: 'Player'}],
    teamAScore: {type: Number, default: 0},
    teamBScore: {type: Number, default: 0},
    pichichi: [{type: mongoose.Types.ObjectId, ref: 'Player'}],
    mvp: {type: mongoose.Types.ObjectId, ref: 'Player', default:null},
});

"teamA""teamB" 是包含每个玩家的 "_id" 的列表。检索球员时,我想检索 he/she 参加的比赛数。我怎样才能做到这一点?在我的查询下方,只是从模型“Player”

中检索字段
class PlayerController {

    getAll(req, res) {
        Player.find()
            .sort('firstname')
            .exec(function(err, players) {
                res.send(players);
            });
    }
}

所以,除了这个列表之外:

    [
      {
        _id: new ObjectId("6232395d08663294b412d6a1"),
        firstname: 'Sam',
        lastname: 'Credington',
        __v: 0
      },
      {
        _id: new ObjectId("622479f39be8118a52af70e5"),
        firstname: 'Santi',
        lastname: 'Futsal',
        __v: 0
      },
      {
        _id: new ObjectId("6232399608663294b412d6b9"),
        firstname: 'Tom',
        lastname: 'Hendry',
        __v: 0
      }
    ]

我想知道每个球员参加的比赛数量:

[
  {
    _id: new ObjectId("6232395d08663294b412d6a1"),
    firstname: 'Sam',
    lastname: 'Credington',
    matches:6,

    __v: 0
  },
  {
    _id: new ObjectId("622479f39be8118a52af70e5"),
    firstname: 'Santi',
    lastname: 'Futsal',
    matches:8,
    __v: 0
  },
  {
    _id: new ObjectId("6232399608663294b412d6b9"),
    firstname: 'Tom',
    lastname: 'Hendry',
    matches: 2,
    __v: 0
  }
]

这是您可以做到的一种方法。

db.players.aggregate([
  {
    "$lookup": {
      "from": "matches",
      "let": { "myId": "$_id" },
      "pipeline": [
        {
          "$match": {
            "$expr": {
              "$in": [ "$$myId", { "$setUnion": [ "$teamA", "$teamB" ] } ]
            }
          }
        },
        { "$count": "numMatches" }
      ],
      "as": "matchCount"
    }
  },
  {
    "$set": {
      "matches": {
        "$ifNull": [ { "$first": "$matchCount.numMatches" }, 0 ]
      }
    }
  },
  { "$unset": "matchCount" }
])

mongoplayground.net 上试用。