Mongodb查找每个组的最新版本,并在Spring boot中实现
我是mongodb的新手。假设我有一个集合中的文档:Mongodb查找每个组的最新版本,并在Spring boot中实现,mongodb,spring-boot,aggregation-framework,mongotemplate,Mongodb,Spring Boot,Aggregation Framework,Mongotemplate,我是mongodb的新手。假设我有一个集合中的文档: [ { _id: ObjectId("1"), uid: "test", obj: Object name: "a", field1: "..." }, { _id: ObjectId("2"), uid: "t
[
{
_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的obj列表,预期输出为:
[
{
_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: "..."
}
]
我对实现这一目标的想法是:
{
_id:"a"
},
{
_id:"b"
}
第二个问题:
如何使用SpringBootMongo模板或其他SpringBootMongo库进行此类查询
Public class A {
private String _id;
private String uid;
private Obj obj;
}
Public class Obj {
private String name;
private String field1;
}
在Java意义上,我想检索List
但是我不知道怎么做
非常感谢您的帮助。非常简单。遵循规则 添加以下代码:
//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);
//将此代码添加到服务类
@自动连线
私有MongoTemplate MongoTemplate;
...
//聚合管道
聚合agg=Aggregation.newAggregation(
Aggregation.match(标准,其中“uid”为“测试”),
聚合.sort(Direction.DESC,“_id”),
聚合集团(“obj.name”)。首先(“obj”)。作为(“obj”),
聚合.replaceRoot(“obj”)
);
AggregationResults=mongoTemplate.aggregate(agg,“collection”,Obj.class).getMappedResults();
//result.forEach(System.out::println);
谢谢您的回答。我想问一下,如果我的obj类有多个字段,我是否需要使用。首先针对每个字段,还是有一种方法可以使用一个函数获取所有字段?@Aerondight您可以使用$first
运算符获取整个obj
。然后,您需要添加额外的Aggregation.replaceRoot()
stage。再次检查我的答案。