Search code examples
javamongodbbson

How to get a readable string from BSON object


I have a org.bson.conversions.Bson object that I'd like to turn into something readable for debugging.

I've tried using the Mongo JSON util for this, but i get RuntimeExceptions, saying it can't serialize the type com.mongodb.client.model.Filters$AndFilter

Bson query = ...
String json = com.mongodb.util.JSON.serialize(query);

Which does tell me something about the structure of the BSON, but I'd still like to have it readable somehow.


Solution

  • You can convert a Bson instance to a BsonDocument using toBsonDocument and then use BsonDocument.toJson().

    For example ...

    Bson bson = Filters.eq("name", "Bob");
    
    BsonDocument asBsonDocument = bson.toBsonDocument(BsonDocument.class, 
        MongoClient.getDefaultCodecRegistry());
    
    System.out.println(asBsonDocument.toJson());
    

    ... will print:

    { "name" : "Bob" }