英文:
How can I retrieve specifc field without using loop in a return statement with MongoDB and Java?
问题
@Override
public User get(Object userId) {
FindIterable<User> userTbl = database.getCollection("User", User.class).find();
for (User doc : userTbl) {
String id = doc.getId().toHexString();
System.out.println("_id = " + id);
if (id.equals(userId)) {
return doc;
}
}
return null;
}
英文:
I have below working code using for loop to iterate all the id in the user collection. Although this post could help me to this question, it returns specific value as well. I wonder how to get the same result without using it because I can't complete the return statement.
@Override
public User get(Object userId) {
FindIterable<User> userTbl = database.getCollection("User", User.class).find();
for (User doc : userTbl) {
String id = doc.getId().toHexString();
System.out.println("_id = " + id);
if (id.equals(userId)) {
return doc;
}
}
return null;
}
答案1
得分: 1
好的,如果你只想返回一个字段,那就这样做。
@Override
public String get(Object userId) {
FindIterable<User> userTbl = database.getCollection("User", User.class).find();
for (User doc : userTbl) {
String id = doc.getId().toHexString();
System.out.println("_id = " + id);
if (id.equals(userId)) {
return doc.getUser();
}
}
return null;
}
但是使用 MongoRepository 应该会更方便,可以更轻松地访问你的数据。
Repository 示例类(使用 Spring):
@Repository
public interface UserRepository extends MongoRepository<User, String> {
}
以及你的 get() 方法:
@Autowired
private UserRepository userRepository;
@Override
public Optional<String> get(String userId) {
Optional<User> user = userRepository.findById(userId);
if (user.isPresent()) {
return Optional.of(user.get().getId());
}
return Optional.empty();
}
英文:
Well, if you just want to return one field, just do so.
@Override
public String get(Object userId) {
FindIterable<User> userTbl = database.getCollection("User", User.class).find();
for (User doc : userTbl) {
String id = doc.getId().toHexString();
System.out.println("_id = " + id);
if (id.equals(userId)) {
return doc.getUser();
}
}
return null;
}
But it should be easier to use a MongoRepository to get easier access to your data.
Repository example class (with Spring):
@Repository
public interface UserRepository extends MongoRepository<User, String> {
}
And your get() method:
@Autowired
private UserRepository userRepository;
@Override
public Optional<String> get(String userId) {
Optional<User> user = userRepository.findById(userId);
if (user.isPresent()) {
return Optional.of(user.get().getId());
}
return Optional.empty();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论