如何直接从 Java 中的 mongodb 查询返回原始 JSON?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18304516/
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
How to return raw JSON directly from a mongodb query in Java?
提问by pdeva
I have the following code:
我有以下代码:
@RequestMapping(value = "/envinfo", method = RequestMethod.GET)
@ResponseBody
public Map getEnvInfo()
{
BasicQuery basicQuery = new BasicQuery("{_id:'51a29f6413dc992c24e0283e'}", "{'envinfo':1, '_id': false }");
Map envinfo= mongoTemplate.findOne(basicQuery, Map.class, "jvmInfo");
return envinfo;
}
As you can notice, the code:
如您所见,代码:
- Retrieves JSON from MongoDB
- Converts it to a
Map
object - The
Map
object is then converted to JSON by Spring MongoData before it is returned to the browser.
- 从 MongoDB 中检索 JSON
- 将其转换为
Map
对象 - 该
Map
对象然后在返回到浏览器之前由 Spring MongoData 转换为 JSON。
Is it possible to directly return the raw json from MongoDb without going through the intermediate conversion steps?
是否可以直接从 MongoDb 返回原始 json 而不经过中间转换步骤?
采纳答案by Oliver Drotbohm
There's two way's you can do this right now:
您现在可以通过两种方式执行此操作:
1. Using the CollectionCallback
on MongoTemplate
1. 使用CollectionCallback
上MongoTemplate
You can use a CollectionCallback
to deal with the returned DBObject
directly and simply toString()
it:
您可以使用 a直接CollectionCallback
处理返回的DBObject
并简单地处理toString()
它:
template.execute("jvmInfo", new CollectionCallback<String>() {
String doInCollection(DBCollection collection) {
DBCursor cursor = collection.find(query)
return cursor.next().toString()
}
}
Yo'll still get the exception translation into Spring's DataAccessExceptions
. Note, that this is slightly brittle as we expect only a single result to be returned for the query but that's probably something you have to take care of when trying to produce a String
anyway.
你仍然会得到异常翻译成 Spring 的DataAccessExceptions
. 请注意,这有点脆弱,因为我们希望查询只返回一个结果,但这可能是您在尝试生成 a 时必须注意的事情String
。
2. Register a Converter
from DBObject
to String
2.注册一个Converter
从DBObject
到String
You can implement a Spring Converter
to do the toString()
for you.
你可以实现一个 SpringConverter
来toString()
为你做这些。
class DBObjectToStringConverter implements Converter<DBObject, String> {
public String convert(DBObject source) {
return source == null ? null : source.toString();
}
}
You can then either use the XML configuration or override customConversions()
to return a new CustomConversions(Arrays.asList(new DBObjectToStringConverter()))
to get it registered with your MongoConverter
. You can then simply do the following:
然后,您可以使用 XML 配置或覆盖customConversions()
以返回 anew CustomConversions(Arrays.asList(new DBObjectToStringConverter()))
以将其注册到您的MongoConverter
. 然后,您可以简单地执行以下操作:
String result = mongoTemplate.findOne(basicQuery, String.class, "jvmInfo");
I will add the just showed converter to Spring Data MongoDB and register it by default for the upcoming 1.3 GA release and port the fix back to 1.2.x as part of the fix for DATAMONGO-743.
我将刚刚显示的转换器添加到 Spring Data MongoDB 并在默认情况下为即将发布的 1.3 GA 版本注册它,并将修复移植回 1.2.x 作为修复DATAMONGO-743 的一部分。
回答by CorayThan
As Oliver points out, you can use Spring Data for that, but an alternative which you may or may not prefer would be to use MongoDB's more low-level Java Driver. Take a look at the MongoDB Java Driver 3.xor MongoDB Java Driver 2.xdocumentation for instructions on using that driver.
正如 Oliver 指出的那样,您可以使用 Spring Data,但您可能喜欢或不喜欢的替代方法是使用 MongoDB 的更底层的 Java 驱动程序。有关使用该驱动程序的说明,请查看MongoDB Java Driver 3.x或MongoDB Java Driver 2.x文档。
Basically, what you need to do is this:
基本上,你需要做的是:
MongoDB Java Driver 3.x
MongoDB Java 驱动程序 3.x
MongoClient mongoClient = new MongoClient();
MongoDatabase db = mongoClient.getDatabase("test");
MongoCollection coll = db.getCollection("testCollection");
BasicDBObject query = new BasicDBObject("_id", "51a29f6413dc992c24e0283e");
try (MongoCursor<Document> cursor = collection.find(query).iterator()) {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
}
MongoDB Java Driver 2.x
MongoDB Java 驱动程序 2.x
MongoClient mongoClient = new MongoClient();
DB db = mongoClient.getDB("test");
DBCollection coll = db.getCollection("testCollection");
BasicDBObject query = new BasicDBObject("_id", "51a29f6413dc992c24e0283e");
try (DBCursor cursor = coll.find(query)) {
while(cursor.hasNext()) {
System.out.println(cursor.next());
}
}
That will print out all the documents in the collection that have a field _id
with a value 51a29f6413dc992c24e0283e
.
这将打印出集合中具有_id
value字段的所有文档51a29f6413dc992c24e0283e
。