MongoDB将数据获取到java对象中
我对MongoDb很陌生。我使用find并以JSON格式获取结果MongoDB将数据获取到java对象中,java,mongodb,Java,Mongodb,我对MongoDb很陌生。我使用find并以JSON格式获取结果 {"Name": "Harshil", "Age":20} 所以我需要的是用java解析它,并在变量中获取值 String name should contain Harshil int age should contain 20 有没有办法将这些详细信息存储在JAVA对象中?看看库。它将JSON转换为Java对象,反之亦然。有很多方法和工具,其中之一是 如果我不加上这个,我会觉得很放松。你考虑过了吗 您只需使用Java驱动
{"Name": "Harshil", "Age":20}
所以我需要的是用java解析它,并在变量中获取值
String name should contain Harshil
int age should contain 20
有没有办法将这些详细信息存储在JAVA对象中?看看库。它将JSON转换为Java对象,反之亦然。有很多方法和工具,其中之一是 如果我不加上这个,我会觉得很放松。你考虑过了吗
您只需使用Java驱动程序即可:
DBObject dbo = ...
String s = dbo.getString("Name")
int i = dbo.getInt("Age")
在Java驱动程序之上使用另一个框架应该被视为您有多个对象要管理。以下是如何连接到您的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");
连接后,您可以从服务器中提取数据。下面,我假设您的文档具有名称和年龄字段:
DBObject dbo = collection.findOne();
String name = dbo.get("Name");
int age = dbo.get("Age");
更新的方式[因为getDB()已被弃用]
由于发布了原始答案,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");
老实说,
for
循环并不是一种很好的方法,但我想帮助社区与不推荐作斗争。我更喜欢使用新的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;
}
公共MyEntity findMyEntityById(长entityId){
List queryFilters=new ArrayList();
add(Filters.eq(“_id”,entityId));
Bson searchFilter=Filters.and(queryFilters);
List returnFilters=new ArrayList();
returnFilters.add(Filters.eq(“name”,1));
Bson returnFilter=过滤器和(returnFilters);
Document doc=getMongoCollection().find(searchFilter).projection(returnFilter.first();
JsonParser JsonParser=new JsonFactory().createParser(doc.toJson());
ObjectMapper mapper=新的ObjectMapper();
MyEntity MyEntity=mapper.readValue(jsonParser,MyEntity.class);
回归自我;
}
详情见
由于我们不想使用不推荐使用的方法,因此,您可以使用以下代码执行此操作:
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();
}
MongoClient mongo=新的MongoClient(“localhost”,27017);
MongoDatabase=mongo.getDatabase(“您的数据库名称”);
MongoCollection collection=database.getCollection(“您的集合名称”);
findItemerable iterDoc=collection.find();
MongoCursor dbc=iterDoc.iterator();
while(dbc.hasNext()){
试一试{
JsonParser JsonParser=new JsonFactory().createParser(dbc.next().toJson());
ObjectMapper mapper=新的ObjectMapper();
Person=mapper.readValue(jsonParser,Person.class);
字符串名称=person.get(“name”);
字符串年龄=person.get(“年龄”);
}捕获(例外e){
e、 printStackTrace();
}
Jackson使用JsonFactory、JsonParser等将文档反序列化为相关实体对象。尝试使用此函数将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();
}
您在什么上下文中使用它?如果您使用的是Spring,Spring Data MongoDB将神奇地为您处理它。您需要强制转换get的结果,例如String name=(String)dbo.get(“name”)feel lax的意思?
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;
}
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();
}
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();
}
public class CustomJavaObject{
//your json fields go here
String field1, field2;
int num;
ArrayList<String> attributes;
//....write relevantgetter and setter methods
}
{
"field1": "Hsr Layout",
"field2": "www.google.com",
"num": 20,
"attributes": [
"Benagaluru",
"Residential"
]
},
{
"field1": "BTM Layout",
"field2": "www.youtube.com",
"num": 10,
"attributes": [
"Bangalore",
"Industrial"
]
}