首页 > 解决方案 > 使用 Selenium/Java 从 MongoDB 中检索单个字段

问题描述

我只是从 MySQL 切换到 MongoDB,这有点令人困惑。我们将数据库存储在 MongoDB 中,并在前端使用 Java-Selenium。我试图从数据库中检索一个单一的数据。下面的代码检索数据库中存在的所有数据:

DBCursor cursor = dbCollection.find();

while(cursor.hasNext())
{
    int i=1;
    System.out.println(cursor.next());
    i++;
}

这是我的数据库让我们说:

{
    "name" : "Su_123", 
    "email" : "test@gmail.com", 
    "_id" : ObjectId("12345656565656")
}

我想从文档中仅检索电子邮件字段( test@gmail.com_id = ObjectId("12345656565656") )并将其存储在字符串字段中。

我该如何进行编码?find()检索整行。

标签: mongodbselenium-webdriver

解决方案


对于较新的驱动程序,自 3.7.1 起


要获取与过滤器匹配的特定文档:

Document doc = collection.find(eq("email", "test@gmail.com")).first();

它可用于查找字段email具有值的第一个文档test@gmail.com。并传递一个eq过滤器对象来指定相等条件。

通过相同的逻辑使用id

Document document = myCollection.find(eq("_id", new ObjectId("12345656565656"))).first();

要从所选文档中获取字段的特定值:

String value = (String) doc.get("email");

对于2.14.22.13.3等较旧的驱动程序

使用查询获取单个文档:

BasicDBObject query = new BasicDBObject("email", "test@gmail.com");

cursor = coll.find(query);

try {
   while(cursor.hasNext()) {
       //System.out.println(cursor.next());
   }
} finally {
   cursor.close();
}

要查看更新的 Mongodb Java 驱动程序的更多详细信息。
要查看旧版 Mongodb Java 驱动程序的更多详细信息。
从 Mongodb 官方文档中查看更多详细信息。


推荐阅读