Bson pretty print using Java MongoDb driver

后端 未结 3 1915
暗喜
暗喜 2021-01-06 11:52

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

相关标签:
3条回答
  • 2021-01-06 12:07

    This is a rather old question, however I put my suggestion (for mongodb-driver 3.6.4) here as this is the most relevant post when googling on "mongodb java driver pretty print":

    BsonDocument bsonDocument = bson.toBsonDocument(BsonDocument.class, MongoClient.getDefaultCodecRegistry());
    JsonWriterSettings.Builder settingsBuilder = JsonWriterSettings.builder().indent(true);
    System.out.println(bsonDocument.toJson(settingsBuilder.build());
    
    0 讨论(0)
  • 2021-01-06 12:20

    For mongodb-java API 3.4, the constant MongoClient.DEFAULT_CODEC_REGISTRY is no more accessible directly, it's a private member. There is a static method CodecRegistry getDefaultCodecRegistry() which returns the same constant.

    Another point, BsonDocument.toString() internally does a toJson() with default JsonWriterSettings. In order to see the Shell equivalent of Query, use it like below:

    public void logQuery(Bson filter) {
        if (LOGGER.isDebugEnabled()) {
    
            LOGGER.debug(
                    "filter query: " + filter.toBsonDocument(BsonDocument.class, MongoClient.getDefaultCodecRegistry())
                            .toJson(new JsonWriterSettings(JsonMode.SHELL)));
        }
    }
    
    0 讨论(0)
  • 2021-01-06 12:25

    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);
    

    The original link is the following: Converting Bson object to BsonDocument.

    0 讨论(0)
提交回复
热议问题