Converting Bson object to BsonDocument

3,606 views
Skip to first unread message

Kamesh Bhallamudi

unread,
Oct 14, 2015, 7:18:28 AM10/14/15
to mongodb-user
Hi All,
 I am trying to convert Bson object to BsonDocument object using Bson#toBsonDocument. 
 As the documentation about Bson#toBsonDocument says, parameters are optionals, so, I passed null and null. But in this case, I am getting NPE.

My usage is like this

    Bson bson = Filters.gt("a", 10);
    BsonDocument bsonDocument = bson.toBsonDocument(null, null);
    System.out.println(bsonDocument);

I am using Java Driver version : 3.0.2

Exception

Exception in thread "main" java.lang.NullPointerException
at com.mongodb.client.model.Filters.encodeValue(Filters.java:683)
at com.mongodb.client.model.Filters.access$100(Filters.java:47)
at com.mongodb.client.model.Filters$OperatorFilter.toBsonDocument(Filters.java:527)
Please correct me if I am doing something wrong and help me how do I convert Bson (filter) to BsonDocument.


Ross Lawley

unread,
Oct 14, 2015, 9:28:12 AM10/14/15
to mongodb-user
Hi Kamesh,

I can understand the confusion from the API documentation.  These parameters aren't optional but rather specific implementations of the Bson interface may ignore the values you pass in because they aren't needed for that specific implementation.  As a user you should always provide a value.

In general you shouldn't have to convert Bson types into BsonDocument in the API as this is all taken care of.  Is there a reason you are manually trying to convert them?

With your example try:

    Bson bson = Filters.gt("a", 10);
    BsonDocument bsonDocument = bson.toBsonDocument(BsonDocument.class, MongoClient.DEFAULT_CODEC_REGISTRY);
    System.out.println(bsonDocument);

All the best,

Ross
Reply all
Reply to author
Forward
0 new messages