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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 17:53:31  来源:igfitidea点击:

MongoDB get data into java object

javamongodb

提问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?

Take a look at GSONlibrary. It converts JSON to Java objects and vice-versa.

看看GSON库。它将 JSON 转换为 Java 对象,反之亦然。

回答by Tom

There are many ways and tools, one of which is gson

方法和工具很多,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);   

And I'd feel lax if I didn't add this linktoo.

如果我也不添加此链接,我会感到松懈。

回答by Andrey Chaschev

Have you considere Morphia?

你考虑过吗啡

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

回答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 DBObjectand corresponding method client.getDBhave 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 nameand their ageI 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 ArrayListto 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 forloop 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"
]
}