问题描述
我正在使用Java MongoDB驱动程序3.3版使用Mongo聚合框架。我有一个聚合管道,它只是 List< Bson>
类型的集合。我试图找到一种方法来打印管道的每个阶段。
I am using the Mongo Aggregation Framework using the Java MongoDB driver, version 3.3. I have an aggregagtion pipeline, that is merely collection of type List<Bson>
. I am trying to find a way to pretty print each stage of the pipeline.
在每个阶段调用 toString
方法element是不够的,因为每个阶段都是 Bson
接口的简单实现的实例,它是 SimplePipelineStage
。这个愚蠢的类没有覆盖 toString
方法。
Calling the toString
method on each element is not sufficient, because each stages is an instance of a simple implementation of the Bson
interface, which is SimplePipelineStage
. This stupid class has not any override of the toString
method.
使用mongo java的工厂方法创建管道driver 聚合
类,如下所示:
The pipeline is created using factory methods of mongo java driver Aggregates
class, like the following:
Aggregates.match(/* ... */)
Aggregates.project(/* ... */)
// And so on...
可以找到Javadoc 。
Javadoc can be found here.
我怎样才能打印出这样的物体?我确定类型 BasicDbObject
有一个智能的 toString
实现,但我找不到从 Bson 到 BasicDbObject
。
How can I pretty print such objects? I know for sure that the type BasicDbObject
has a smart toString
implementation, but I cannot find a way to convert from Bson
to BasicDbObject
.
非常感谢提前。
推荐答案
谷歌搜索更难,我找到了一个解决方案,可以打印 Bson
实例。诀窍是将其转换为 BsonDocument
的实例,该实例具有返回字符串的 toString
方法的实现表示相应的JSON。
Googling a bit harder, I found a solution to pretty print a Bson
instance. The trick is to convert it into an instance of BsonDocument
, which has an implementation of the toString
method that returns the string representation of the corresponding JSON.
Bson bson = Filters.gt("a", 10);
BsonDocument bsonDocument = bson.toBsonDocument(BsonDocument.class, MongoClient.DEFAULT_CODEC_REGISTRY);
System.out.println(bsonDocument);
原始链接如下:。
这篇关于使用Java MongoDb驱动程序的Bson漂亮打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!