Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a readable string from BSON object

Tags:

java

mongodb

bson

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.

like image 920
kinbiko Avatar asked Dec 20 '17 10:12

kinbiko


People also ask

How do you parse BSON?

BSON documents are lazily parsed as necessary. To begin parsing a BSON document, use one of the provided Libbson functions to create a new bson_t from existing data such as bson_new_from_data(). This will make a copy of the data so that additional mutations may occur to the BSON document.

Is BSON human-readable?

BSON needs to be parsed as they are machine-generated and not human-readable.

Can you convert BSON to JSON?

Converting a BSON Object to a JSON StringUse the asString method to convert the BSON document to an extended JSON string. See http://docs.mongodb.org/manual/reference/mongodb-extended-json/ for more information on extended JSON.

What is BSON string?

BSON is a binary serialization format used to store documents and make remote procedure calls in MongoDB. The BSON specification is located at bsonspec.org . Each BSON type has both integer and string identifiers as listed in the following table: Type. Number.


1 Answers

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" }
like image 144
glytching Avatar answered Sep 22 '22 05:09

glytching