Find some values in a mongodb collection?(在 mongodb 集合中查找一些值?)
问题描述
Im trying to read a (mongo)userdatabase with java. On the tutorial page I saw how to read the whole collection. I can do something like that:
DBCursor cursor = col.find();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
Now if I have a collection with users := name, age, password (...) and whatever. Now I would like to find a name with a password. For example for a login process. Lets say I have two strings: String n and p. If there is a user.equals(n) and a password.equals(p) in the database then login user. How do I have to change my cursor? I saw some query examples on the mongodb java tutorial page, but duh I really dont get it...
Any ideas? Thank you
Awesome, you'll love Mongo.
In the example you posted, the program iterates through a set of results. In the user/password problem you describe what you are actually trying to do is get one document (not a set of documents) based on some criteria.
On the shell that would look like this:
n = "login"
p = "password"
db.users.findOne({ user: n, password: p})
Notice I'm using findOne instead of find which returns a document instead of a cursor to many documents.
Now, lets take a look at the java driver's example:
BasicDBObject query = new BasicDBObject();
query.put("i", 71);
cur = coll.find(query);
while(cur.hasNext()) {
System.out.println(cur.next());
}
The BasicDBObject creates the query object and then you put different criteria which together form your query.
So instead of query.put("i", 71);
you would do something like:
query.put("user", n)
query.put("password", p)
and... instead of the while loop just use findOne instead of find so you don't have to iterate over the result set of 1 object (pointless).
You can read more about findOne() here.
这篇关于在 mongodb 集合中查找一些值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 mongodb 集合中查找一些值?
基础教程推荐
- Java:带有char数组的println给出乱码 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 降序排序:Java Map 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01