您好,我可以像这样轻松访问 MongoDb 中的数据;
Jar 文件,
bson-3.4.2.jar,
mongodb-driver-3.4.2.jar,
mongodb-driver-async-3.4.2.jar,
mongodb-driver-core-3.4.2.jar
Java
MongoClient mongoClient = new MongoClient("192.168.56.101",27017);
MongoDatabase database = mongoClient.getDatabase("dbTest2");
MongoCollection<Document> collection = database.getCollection("colTest2");
str=Objects.toString(collection.count());
Document myDoc = collection.find().first();
id=Objects.toString(myDoc.get("_id"));
超链接
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
<title>MongoDB Test</title>
</h:head>
<h:body>
<h1>Number of data : #{obj.str}</h1>
<h1>ID : #{obj.id}</h1>
</h:body>
但问题是我如何在其中获取子数据?我所能得到的只是标记,它给了它们两个,我只需要 firstmarker 打印出来;
{
"_id" : "test",
"status" : 2,
"time" : null,
"markers" :{
"firstmarker" : 1,
"secondmarker" : 2,
},
"batchid" : 15000234
}
最佳答案
很简单,因为它是JSON格式,是键值对,你只需要通过提供键来访问值。
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html">
<h:head>
<title>MongoDB Test</title>
</h:head>
<h:body>
<h1>Number of data : #{obj.str}</h1>
<h1>ID : #{obj.id}</h1>
<h1>FirstMarker : #{obj.markers.firstmarker}</h1>
</h:body>
编辑:要访问 java 中的值,请使用以下代码<我使用的是 3.4.2 版的 mongo java 驱动程序。
public static void main(final String[] args) throws UnknownHostException {
final MongoClient mongoClient = new MongoClient("localhost", 27017);
final DB database = mongoClient.getDB("dbTest2");
final DBCollection collection = database.getCollection("colTest2");
final long count = collection.count();
final DBObject dbObject = new BasicDBObject();
dbObject.put("_id", "test");
final DBCursor curr = collection.find(dbObject);
while (curr.hasNext()) {
final DBObject dbo = curr.next();
final BSONObject object = (BSONObject) dbo.get("markers");
System.out.println(object.get("firstmarker"));
}
}
关于java - 如何在 MongoDb 中访问子数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42221481/