mongodb - 使用 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()
检索整行。
解决方案
要获取与过滤器匹配的特定文档:
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");
使用查询获取单个文档:
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 官方文档中查看更多详细信息。
推荐阅读
- php - 带有文件上传和发送到电子邮件的 PHP 表单
- c++ - C++ MySql 连接器 - 查询超出范围的结果
- c++ - 是否可以在 c++17 中为 c 样式指针或原始指针创建弱指针
- python - 如何在 python 上编写正则表达式来查找 2 到 2,000,000,000 之间的值?
- c# - Split, sort and merge string
- java - Regular expression which accept the double quotes only and only if it follows a backslash
- javascript - Issue using getters and setters in p5.js javascript class, "Script error. (: line 0)"
- android - Android 和长时间运行的后台任务
- git - Difference between git push --force vs git push non fast forward update
- node.js - NodeJS MongoDB 动态 find() 查询