java - 如何在 MongoDb 中访问子数据?

标签 java mongodb

您好,我可以像这样轻松访问 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/

相关文章:

0 到 1 之间值的 Java Float 精度

java - 如何解决MongoDB中的 "Digg"问题

spring - 如何在Spring的Mongo和Elastic Search之间共享的实体中使用@Transient之类的通用注释?

arrays - 在嵌套数组mongodb中插入对象nodejs

java - 无法从 PDFA1-a 格式文档中提取图像

java - Java 中的 Base64 编码图像显然是错误的,我错过了什么?

java - 开始制作自己的基于 Android 的媒体中心的好方法

node.js - Mongodb 光标在 ejs 模板中为空(ejs 内的异步调用)

java - 如何使用 java 仅获取 mongodb 中文档的 objectId

java - 在这种情况下,正确的 Java 集合是什么?