Mongodb 找到每个组的最新版本并在 Spring 启动时实现

Mongodb find the latest of each group and implemented in Spring boot

我是 mongodb 的新手。假设我在一个集合中有文档:

  [
        {
          _id: ObjectId("1"),
          uid: "test",
          obj: Object
                    name: "a",
                    field1: "..."
        },

        {
          _id: ObjectId("2"),
          uid: "test",
          obj: Object
                    name: "a",
                    field1: "..."
        },
        {
          _id: ObjectId("3"),
          uid: "test",
          obj: Object
                    name: "b",
                    field1: "..."
        },
         {
          _id: ObjectId("4"),
          uid: "test2",
          obj: Object
                    name: "b",
                    field1: "..."
        }
    ]

我想检索具有唯一性 obj.name 的对象列表,预期输出为:

  [
      {
         _id: ObjectId("2") // not really necessary , just to show that the obj was under ObjectId("2")
         name: "a",
         field1: "..."
      },
      {
         _id: ObjectId("3") // not really necessary , just to show that the obj was under ObjectId("3")
         name: "b",
         field1: "..."
      }
    ]

我的实现想法:

  1. 先匹配uid
  2. 按 _id desc 排序结果
  3. 分组 obj.name

    [{ $匹配:{ uid:"test" } }, { $排序:{ _id: -1 } }, { $组:{ _id: "$obj.name" } }]

我得到了什么:

{
  _id:"a"
},
{
  _id:"b"
}

第二题: 如何使用 Spring boot mongo 模板或其他 spring boot mongo 库进行此类查询?

 Public class A {
       private String _id;
       private String uid;
       private Obj obj;
    }

    Public class Obj {
           private String name;
           private String field1;
    }

在Java意义上,我想检索List<Obj>

但不知道该怎么做。

非常感谢您的帮助。

很简单。关注tutorial.

添加以下代码:

//Add this code to your service class
@Autowired
private MongoTemplate mongoTemplate;

...

//Aggregation pipeline    
Aggregation agg = Aggregation.newAggregation(
    Aggregation.match(Criteria.where("uid").is("test")),
    Aggregation.sort(Direction.DESC, "_id"),
    Aggregation.group("obj.name").first("obj").as("obj"),
    Aggregation.replaceRoot("obj")
);

AggregationResults<Obj> result = mongoTemplate.aggregate(agg, "collection", Obj.class).getMappedResults();
//result.forEach(System.out::println);