Find some values in a mongodb collection?

后端 未结 2 1140
Happy的楠姐
Happy的楠姐 2021-01-19 04:40

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 cu         


        
相关标签:
2条回答
  • 2021-01-19 04:46

    You can query desired data directly:

    BasicDBObject query = new BasicDBObject();
    query.put("name", "user");
    query.put("password", "[YOUR ENCRYPTED PASSWORD HERE]");
    
    DBCollection collection = db.getCollection("yourcollectionname");
    DBCursor cursor = collection.find(query);
    
    while (cursor.hasNext()) {
      //do something with cursor.next();
    }
    

    As was suggested you need to check count of results returned by find() method to make sure only single record matches your query.

    0 讨论(0)
  • 2021-01-19 04:54

    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.

    0 讨论(0)
提交回复
热议问题