在mongodb集合中找到一些值? [英] Find some values in a mongodb collection?
问题描述
我正在尝试使用Java读取(mongo)用户数据库.在教程页面上,我看到了如何阅读整个收藏集.我可以做这样的事情:
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());
}
现在,如果我有一个包含用户的收藏集:=名称,年龄,密码(...)等.现在,我想找到一个带有密码的名称.例如用于登录过程.可以说我有两个字符串:字符串n和p.如果数据库中存在user.equals(n)和password.equals(p),则登录用户.我该如何更改光标?我在mongodb Java教程页面上看到了一些查询示例,但是我真的不明白...
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...
有什么想法吗?谢谢
推荐答案
太棒了,您会爱上Mongo的.
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})
注意,我使用的是findOne而不是find,它会返回一个文档,而不是将光标指向许多文档.
Notice I'm using findOne instead of find which returns a document instead of a cursor to many documents.
现在,让我们看一下Java驱动程序的示例:
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());
}
BasicDBObject创建查询对象,然后将不同的条件组合在一起构成查询.
The BasicDBObject creates the query object and then you put different criteria which together form your query.
因此,代替query.put("i", 71);
,您将执行以下操作:
So instead of query.put("i", 71);
you would do something like:
query.put("user", n)
query.put("password", p)
and ...而不是while循环,而是使用findOne而不是find,因此您不必遍历1个对象的结果集(毫无意义).
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).
您可以阅读有关findOne()的更多信息此处.
You can read more about findOne() here.
这篇关于在mongodb集合中找到一些值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!