8

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.

kinbiko
  • 2,066
  • 1
  • 28
  • 40

1 Answers1

11

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" }
glytching
  • 44,936
  • 9
  • 114
  • 120