2013-10-22 42 views
0

我對MongoDb相當陌生。我使用查找並以JSON格式獲得結果。MongoDB獲取數據到java對象

{"Name": "Harshil", "Age":20} 

所以我需要的是解析這個在Java中,並獲得變量的值。

String name should contain Harshil 
int age should contain 20 

有沒有辦法將這些細節存儲在JAVA對象中?

+1

public MyEntity findMyEntityById(long entityId) { List<Bson> queryFilters = new ArrayList<>(); queryFilters.add(Filters.eq("_id", entityId)); Bson searchFilter = Filters.and(queryFilters); List<Bson> returnFilters = new ArrayList<>(); returnFilters.add(Filters.eq("name", 1)); Bson returnFilter = Filters.and(returnFilters); Document doc = getMongoCollection().find(searchFilter).projection(returnFilter).first(); JsonParser jsonParser = new JsonFactory().createParser(doc.toJson()); ObjectMapper mapper = new ObjectMapper(); MyEntity myEntity = mapper.readValue(jsonParser, MyEntity.class); return myEntity; } 

詳情您在使用本什麼情況下?如果你使用Spring,Spring Data MongoDB會爲你處理這個問題。 – chrylis

回答

5

下面是如何連接到您的MongoDB:

MongoClient client = new MongoClient("localhost",27017); //with default server and port adress 
DB db = client.getDB("your_db_name"); 
DBCollection collection = db.getCollection("Your_Collection_Name"); 

後連接您可以從server.Below拉你的數據,我認爲你的文檔中有姓名和年齡字段:

DBObject dbo = collection.findOne(); 
String name = dbo.get("Name"); 
int age = dbo.get("Age"); 
+1

您需要輸入獲得的結果,例如String name =(String)dbo.get(「Name」) – Trisha

4

看看GSON庫。它將JSON轉換爲Java對象,反之亦然。

3

有很多方法和工具,其中之一是gson

class Person { 
    private String name; 
    private int age; 
    public Person() { 
     // no-args constructor 
    } 
} 

Gson gson = new Gson(); 
Person person = gson.fromJson(json, Person.class); 

而且我覺得鬆懈,如果我不添加此link了。

+0

鏈接已死亡 – ThisClark

+0

修復了鏈接。 – Tom

+0

覺得鬆懈的手段? –

0

你有沒有考慮Morphia

@Entity 
class Person{ 
    @Property("Name") Date name; 
    @Property("Age") Date age; 
} 
1

你可以只用Java驅動程序做到這一點:

DBObject dbo = ... 
String s = dbo.getString("Name") 
int i = dbo.getInt("Age") 

使用於Java驅動程序之上另一個框架,應考慮我你有多個對象來管理。

0

由於最初的答案已發佈,DBObject和相應的方法client.getDB已被棄用。對於任何可能在新版本更新後尋找解決方案的人,我已盡力翻譯。

MongoClient client = new MongoClient("localhost",27017); //Location by Default 
MongoDatabase database = client.getDatabase("YOUR_DATABASE_NAME"); 
MongoCollection<Document> collection = database.getCollection("YOUR_COLLECTION_NAME"); 

連接到文檔後,有許多熟悉的將數據作爲Java對象的方法。假設你打算有多個文檔包含一個人name及其age我建議在ArrayList中收集所有文檔(你可以將其視爲包含名稱和年齡的行),然後你可以簡單地選擇ArrayList中的文檔進行轉換他們到Java對象像這樣:

List<Document> documents = (List<Document>) collection.find().into(new ArrayList<Document>()); 
for (Document document : documents) { 
    Document person = documents.get(document); 
    String name = person.get("Name"); 
    String age = person.get("Age"); 
} 

老實說for循環不是做一個漂亮的方式,但我想幫助社區棄用掙扎。