MongoDB获取数据到java对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19510832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MongoDB get data into java object
提问by Harshil Shah
I am quite new to MongoDb. i use a find and get the result in JSON format.
我对 MongoDb 很陌生。我使用查找并以 JSON 格式获取结果。
{"Name": "Harshil", "Age":20}
so what i need is parse this in java and get values in the variables.
所以我需要的是在java中解析它并获取变量中的值。
String name should contain Harshil
int age should contain 20
is there a way to store these details in JAVA object?
有没有办法将这些细节存储在 JAVA 对象中?
采纳答案by myildirim
Here is how to connect to the your MongoDB:
以下是连接到 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");
After the connecting you can pull your data from the server.Below, i assume that your document has Name and Age field :
连接后,您可以从服务器中提取数据。下面,我假设您的文档具有 Name 和 Age 字段:
DBObject dbo = collection.findOne();
String name = dbo.get("Name");
int age = dbo.get("Age");
回答by Mustafa Gen?
回答by Tom
回答by Andrey Chaschev
回答by Yann Moisan
You can just do it with the Java driver :
您可以使用 Java 驱动程序来完成:
DBObject dbo = ...
String s = dbo.getString("Name")
int i = dbo.getInt("Age")
Using another framework on top of the Java driver should be considered I you have multiple objects to manage.
在 Java 驱动程序之上使用另一个框架应该被视为我有多个对象要管理。
回答by Thomas Rokicki
Newer Way [Since getDB() is Deprecated]
较新的方式 [因为 getDB() 已弃用]
Since the original answer was posted the DBObject
and corresponding method client.getDB
have been deprecated. For anyone who may be looking for a solution since the new update I have done my best to translate.
由于发布了原始答案,因此不推荐使用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");
Once connected to the document there are numerous familiar methods of getting data as a Java Object. Assuming you plan to have multiple documents that contain a persons name
and their age
I suggest collecting all the documents (which you can visualize as rows containing a name and age) in an ArrayList then you can simply pick through the documents in the ArrayList
to convert them to java objects as so:
一旦连接到文档,就有许多熟悉的方法可以将数据作为 Java 对象获取。假设您计划拥有包含一个人和name
他们的多个文档,age
我建议在 ArrayList 中收集所有文档(您可以将其可视化为包含姓名和年龄的行),然后您可以简单地选择 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");
}
Honestly the for
loop is not a pretty way of doing it but I wanted to help the community struggling with deprecation.
老实说,for
循环并不是一个很好的方法,但我想帮助社区在弃用中挣扎。
回答by Ashutosh Srivastav
I would prefer using the new Mongodb Java API. It's very clean and clear.
我更喜欢使用新的 Mongodb Java API。它非常干净和清晰。
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;
}
Details at http://ashutosh-srivastav-mongodb.blogspot.in/2017/09/mongodb-fetch-operation-using-java-api.html
详情见 http://ashutosh-srivastav-mongodb.blogspot.in/2017/09/mongodb-fetch-operation-using-java-api.html
回答by Akshay Bhardwaj
As we don't want to use the deprecated methods so, you can use the following code to do so:
由于我们不想使用已弃用的方法,因此您可以使用以下代码来执行此操作:
MongoClient mongo = new MongoClient( "localhost" , 27017 );
MongoDatabase database = mongo.getDatabase("your_db_name");
MongoCollection<Document> collection = database.getCollection("your_collection_name");
FindIterable<Document> iterDoc = collection.find();
MongoCursor<Document> dbc = iterDoc.iterator();
while(dbc.hasNext()){
try {
JsonParser jsonParser = new JsonFactory().createParser(dbc.next().toJson());
ObjectMapper mapper = new ObjectMapper();
Person person = mapper.readValue(jsonParser, Person.class);
String name = person.get("Name");
String age = person.get("Age");
} catch (Exception e){
e.printStackTrace();
}
JsonFactory, JsonParser,etc. are being used from Hymanson to de-serialize the Document to the related Entity object.
JsonFactory、JsonParser 等 Hymanson 正在使用它来将文档反序列化为相关的实体对象。
回答by arnav
Try Using this function to convert JSON returned by mongodb to your custom java object list.
尝试使用此函数将 mongodb 返回的 JSON 转换为您的自定义 java 对象列表。
MongoClient mongodb = new MongoClient("localhost", 27017);
DB db = mongodb.getDB("customData-database");
DBCursor customDataCollection = db.getCollection("customDataList").find();
List<CustomJavaObject> myCustomDataList = null; // this list will hold your custom data
JSON json = new JSON();
ObjectMapper objectMapper = new ObjectMapper();
try {
//this is where deserialiazation(conversion) takes place
myCustomDataList = objectMapper.readValue(json.serialize(customDataCollection),
new TypeReference<List<Restaurant>>() {
});
} catch (IOException e) {
e.printStackTrace();
}
CustomJavaObject:
自定义Java对象:
public class CustomJavaObject{
//your json fields go here
String field1, field2;
int num;
ArrayList<String> attributes;
//....write relevantgetter and setter methods
}
sample json:
示例json:
{
"field1": "Hsr Layout",
"field2": "www.google.com",
"num": 20,
"attributes": [
"Benagaluru",
"Residential"
]
},
{
"field1": "BTM Layout",
"field2": "www.youtube.com",
"num": 10,
"attributes": [
"Bangalore",
"Industrial"
]
}