是否可以添加另一个字段来查找和过滤 java 中 mongodb 数据库中的结果?



>我正在尝试从mongodb数据库中取回一个文档,但我只想获取用户名和密码等于我正在传入的值的文档。我有以下代码,我的问题是,如何添加另一个字段(密码(来过滤结果?目前我只按用户名过滤,但我不知道如何添加另一个字段来搜索:

public Employee getEmployee(String username, String password) {
    FindIterable<Document> findIterable = collection.find(new BasicDBObject("Username", username));
    MongoCursor<Document> cursor = findIterable.iterator();
    Employee e = new Employee();
    if (cursor.hasNext()) {
        Document doc = cursor.next();
        //ArrayList<Object> o = new ArrayList<>(doc.values());
        e.setId(doc.get("_id").toString());
        e.setName(doc.get("Name").toString());
        e.setAddress(doc.get("Address").toString());
        e.setEmail(doc.get("Email").toString());
        e.setPhone(doc.get("Phone").toString());
        e.setUsername(doc.get("Username").toString());
        e.setPassword(doc.get("Password").toString());
    }
    return e;//Get the shoes
}

是的,这是可能的,您可以轻松添加另一个查询,BasicDBObject查看 JAVA API 文档以了解详细信息:

https://api.mongodb.com/java/2.6/com/mongodb/BasicDBObject.html

在本文档中搜索append方法,您可以从该文档中.append上一个对象,如下所示:

public Employee getEmployee(String username, String password) {
    //  build the BSON object query
    BasicDBObject query = new BasicDBObject("Username", username).append("Password", password);
    // Execute the query
    FindIterable<Document> findIterable = collection.find(query);
    MongoCursor<Document> cursor = findIterable.iterator();
    Employee e = new Employee();
    if (cursor.hasNext()) {
        Document doc = cursor.next();
        //ArrayList<Object> o = new ArrayList<>(doc.values());
        e.setId(doc.get("_id").toString());
        e.setName(doc.get("Name").toString());
        e.setAddress(doc.get("Address").toString());
        e.setEmail(doc.get("Email").toString());
        e.setPhone(doc.get("Phone").toString());
        e.setUsername(doc.get("Username").toString());
        e.setPassword(doc.get("Password").toString());
    }
    return e;//Get the shoes
}

或者按照评论部分的建议,@ernest_k也可以工作。

引用:

  1. https://mongodb.github.io/mongo-java-driver/3.6/javadoc/?com/mongodb/BasicDBObject.html

  2. https://api.mongodb.com/java/2.6/com/mongodb/BasicDBObject.html

Document 类的 append 方法可用于为筛选器添加多个条件,如下所示(这只是使用另一种方式(。

FindIterable<Document> findIterable = collection.find(new Document("Username", username).append("Password", password));

-或-

Document filter = new Document("Username", username).append("Password", password);
// -or-
Document filter = new Document().append("Username", username).append("Password", password);
FindIterable<Document> findIterable = collection.find(filter);

最新更新