簡體   English   中英

如何在不使用 MongoDB 和 Java 的返回語句中使用循環的情況下檢索特定字段?

[英]How can I retrieve specifc field without using loop in a return statement with MongoDB and Java?

我有以下工作代碼使用 for 循環來迭代用戶集合中的所有 id。 雖然這篇文章可以幫助我解決這個問題,但它也會返回特定的值。 我想知道如何在不使用它的情況下獲得相同的結果,因為我無法完成 return 語句。

@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;
}

好吧,如果你只想返回一個字段,就這樣做。

@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 更容易訪問您的數據應該更容易。

存儲庫示例類(使用 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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM