首页 > 解决方案 > MongoDB 查找与正则表达式匹配且价格最高的文档

问题描述

示例文档:

{"_id": <id>, "name" : "Bread_1", "version" : 1 }
{"_id": <id>, "name" : "Bread_2", "version" : 1 }
{"_id": <id>, "name" : "Bread_1", "version" : 2 }
{"_id": <id>, "name" : "Bread_2", "version" : 2 }
{"_id": <id>, "name" : "Bread_3", "version" : 1 }

所需输出:

{"_id": <id>, "name" : "Bread_1", "version" : 2 }
{"_id": <id>, "name" : "Bread_2", "version" : 2 }
{"_id": <id>, "name" : "Bread_3", "version" : 1 }

它是按名称和最大版本分组的。我试过这个查询:

db.products.aggregate({$group: {_id: {name: '$name'}, version: {$max: '$version'}}});

实际输出:

{"_id": {"name" : "Bread_1"}, "version" : 2 }
{"_id": {"name" : "Bread_2"}, "version" : 2 }
{"_id": {"name" : "Bread_3"}, "version" : 1 }

虽然我也需要文档的 ID。在这种情况下我错过了什么?谢谢

标签: mongodbmongodb-queryaggregation-framework

解决方案


没有直接的方法可以得到它,所以你可以试试下面的查询:

db.products.aggregate([
  /** Group on 'name' & get max of 'version' & push all docs to 'docs' array field */
  {
    $group: {
      _id: "$name",
      version: { $max: "$version" },
      docs: { $push: "$$ROOT" }
    }
  },
  /** Transform fields in required format, Iterate over docs array & get '_id' of doc where version do match */
  {
    $project: {
      name: "$_id",
      version: 1,
      _id: {
        $let: {
          vars: {
            id: {
              $arrayElemAt: [ // As filter returns an array get first doc, There can only be one doc
                {
                  $filter: {
                    input: "$docs",
                    cond: { $eq: ["$$this.version", "$version"] } // Check max version == current object's version
                  }
                },
                0
              ]
            }
          },
          in: "$$id._id"
        }
      }
    }
  }
]);

测试: MongoDB-游乐场


推荐阅读