如何使用 spring 数据 mongorepository 方法仅获取选定的 mongo id? [英] How to fetch only selected mongo ids using spring data mongorepository method?
本文介绍了如何使用 spring 数据 mongorepository 方法仅获取选定的 mongo id?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试这个,它一次只对一个 ID 有效.我想添加 ID 列表.
I am trying this, it works for only one id at a time. I want to add list of ids.
public interface collectionRepository extends MongoRepository<collection, String> {
List<collection> findByIds(List<UUID> id);
}
有人可以提出一些想法吗?提前感谢您的帮助!
Could anyone suggest some ideas?Thank you for your help in advance!
推荐答案
这适用于 POJO 类如下的情况:
This works for a case where the POJO class is like:
public class User {
private String id;
private String firstName;
private String lastName;
// constructors (including default), get/set methods, etc.
}
并且,文档存储在集合 user
中,例如:
And, the documents are stored in a collection user
as, for example:
{ "_id" : ObjectId("604827bf8187ce707fb88681"), "firstName" : "John", "lastName" : "Doe", "_class" : "com.example.demo.User" }
具有获取具有提供的 id 列表的对象的方法的存储库:
The repository with the method to fetch the objects with the supplied list of ids:
public interface UserRepository extends MongoRepository<User, String> {
@Aggregation(pipeline = { " { '$match': { '_id': { '$in': ?0 } } }" } )
List<User> findByIdsIn(List<String> ids);
}
对存储库方法的调用:
List<String> inputIds = Arrays.asList("604827d13de5773133374acc", "604827617a40155f5111b9ff");
List<User> outputList = userRepository.findByIdsIn(inputIds);
outputList
有 两个 文档与变量 inputIds
中的 id 匹配.
The outputList
has the two documents matching the ids from the variable inputIds
.
这篇关于如何使用 spring 数据 mongorepository 方法仅获取选定的 mongo id?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文