如何到达MongoDb中的子数据?

时间:2017-02-14 08:47:33

标签: java mongodb

您好我可以轻松地在MongoDb中获取数据;

Jar文件,

  

BSON-3.4.2.jar,
  MongoDB的驱动-3.4.2.jar,
  MongoDB的驱动器 - 异步-3.4.2.jar,
  mongodb的驱动器芯-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"));

HTLM

<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>

但问题是如何在此处访问子数据?我所能得到的只是标记,它给了它们两个,我只需要一个标记打印出来;

{ 
   "_id" : "test",
   "status" : 2,
   "time" : null,
   "markers" :{
         "firstmarker" : 1,
         "secondmarker" : 2,
   },
   "batchid" : 15000234
}

1 个答案:

答案 0 :(得分:1)

非常简单,因为它是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中使用以下代码访问值&lt;我正在使用版本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"));
}
}