2017-02-14 11 views
2

こんにちは私はこのようにMongoDbのデータに簡単にアクセスできます。MongoDbのサブデータに到達する方法は?

JARファイル、

BSON-3.4.2.jar、
MongoDBのドライバ-3.4.2.jar、
MongoDBのドライバ-非同期3.4.2.jar、
のMongoDB -driverコア-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

非常に単純ですが、キーと値のペアである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を使用しているコード<以下の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")); 
} 
} 
+0

よう

何かはありがとうございました! Javaのフォルダ内のオブジェクトとしてオブジェクトを取り込む方法はありますか? –

+0

"Javaフォルダ"はどういう意味ですか? – Apollo

+0

私はJavaの部分を意味し、申し訳ありません。 Javaでサブデータを変更する必要があるとしますが、最初のオブジェクトにしか到達できないとしましょう。 –

0

このようなことを試すことができます。

Document myDoc = collection.find().first(); 
id=Objects.toString(myDoc.get("markers", Document.class).getInteger("firstmarker")); 

クエリにsortを追加することを検討してください。 firstは、自然順序または挿入順序でソートされた文書を提供します。

Document myDoc = collection.find().sort("sort field").first() 
+0

それは文字列を整数にキャストすることはできませんが、私は 'getString( "firstmarker")' 。ありがとうございました! –

関連する問題