【问题标题】:Retrieving a single field from MongoDB using Selenium/Java使用 Selenium/Java 从 MongoDB 检索单个字段
【发布时间】:2020-01-16 07:38:52
【问题描述】:

我只是从 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")
}

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

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

【问题讨论】:

  • 你看过说明书吗?我使用的驱动程序允许使用find(filter, format),其中filter 是您要匹配的内容,format 是您希望在结果中出现的字段。 See here.

标签: mongodb selenium-webdriver


【解决方案1】:

For newer drivers, since 3.7.1


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

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

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

By the same logic 使用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();
}

To see more details for newer Mongodb Java driver.
To see more details for older Mongodb Java driver.
To see more details from Mongodb Official Docs.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-25
    • 2012-02-01
    • 2021-01-07
    • 1970-01-01
    相关资源
    最近更新 更多