简体   繁体   English

集合的返回类型。使用 java 在 mongodb 中查找

[英]Return type of collection.find in mongodb using java

I am trying to implement a simple login function using java where a user enters a username and password through a text field and then these credentials are checked against a set of documents in a collection in mongodb, using maven dependencies. I am trying to implement a simple login function using java where a user enters a username and password through a text field and then these credentials are checked against a set of documents in a collection in mongodb, using maven dependencies. The connection with the database has been made and relevant imports added.已建立与数据库的连接并添加了相关导入。

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import static com.mongodb.client.model.Filters.and;
import static com.mongodb.client.model.Filters.eq;

String user  = txtUser.getText();
String pass = txtPass.getText();

MongoDatabase db = DbConnection.getDbConnection();
MongoCollection collection = db.getCollection("Admin");
FindIterable<Document> findLogin = collection.find(and(eq("username", user),eq("password",pass)));

if(findLogin == null){
     System.out.println("Failed");
}else{
      System.out.println("Successful");
}

The problem here is that successful is displayed even when the wrong credentials are entered.这里的问题是即使输入了错误的凭据也会显示成功。 This is my first time using mongodb so I am not entirely sure of the queries that can be run on mongodb.这是我第一次使用 mongodb,所以我不完全确定可以在 mongodb 上运行的查询。 What type of value does the collection.find return. collection.find 返回什么类型的值。 And what are the possible methods I could follow to overcome the problem?我可以遵循哪些可能的方法来克服这个问题?

The FindIterable returned by the find() method of MongoCollection will not be null . MongoCollection 的find()方法返回的FindIterable不会是null In order to determine whether any documents were matched by your query, you need to inspect the FindIterable .为了确定您的查询是否匹配任何文档,您需要检查FindIterable

In your case, the first() method is the most appropriate.在您的情况下, first()方法是最合适的。 This way you get a single document to perform a null check on.这样,您可以获得一个文档来执行 null 检查。 Put all together it may look like this:放在一起它可能看起来像这样:

Document loginDoc = collection.find(and(eq("username", user),eq("password",pass))).first();

if (loginDoc == null) {
     System.out.println("Failed");
} else {
     System.out.println("Successful");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM