Mongoose 聚合 $match distinct 基于另一个字段?

Mongoose aggregation $match distinct based on another field?

我有一个 collection 这样的:

[
  {
    "ticketNumber" : "00001",
    "version" : "0"
  },
  {
    "ticketNumber" : "00001",
    "version" : "1"
  },
  {
    "ticketNumber" : "00001",
    "version" : "2"
  },
  {
    "ticketNumber" : "00002",
    "version" : "0"
  },
  {
    "ticketNumber" : "00003",
    "version" : "0"
  },
  {
    "ticketNumber" : "00003",
    "version" : "1"
  }
]

该模型具有我将在以后的聚合管道中使用的附加属性。我首先需要以某种方式进行过滤,以便 returns 基于不同的 ticketNumber 和最新版本的门票:

[
  {
    "ticketNumber" : "00001",
    "version" : "2"
  },
  {
    "ticketNumber" : "00002",
    "version" : "0"
  },
  {
    "ticketNumber" : "00003",
    "version" : "1"
  }
]

不确定这是否 do-able 不知何故?

您可以使用 "version" 上的 aggregation framework. It's a simple $group operation using the $max 运算符执行此操作:

db.collection.aggregate([
    { "$group": {
        "_id": "$ticketNumber",
        "version":  { "$max": "$version" }
])

如果 "version" 不是字符串会更好,但它仍然有效,因为即使作为数字字符串,它仍然是词法的。但是“10”在词汇上并不大于“2”。所以要小心。