6

I'm using Java Driver for MongoDB (2.14) in my application.
I have these documents:

{ "_id" : ObjectId("56fb9798e2445ade35effa89"), "b" : BinData(3,"abcdefgh") }
{ "_id" : ObjectId("56fba265e2445ade35effa8c"), "b" : 1 }

I have to retrieve all documents where "b" is a binary data using Java. To reach my target I use the following query:

DBObject query = new BasicDBObject(b, new BasicDBObject("$type",5));
DBObject projKeys = new BasicDBObject();
projKeys.put("_id", 0);
projKeys.put(b, 1);

DBCursor cursor = coll.find(query,projKeys);

But when I start to iterate over cursor I get an exception:

java.lang.IllegalArgumentException: bad data size subtype 3 len: 6 != 16

When I try to make the same query using mongo shell, that is:

db.coll.find({b:{"$type":5}}, {_id:0,b:1})

I don't have errors.

1 Answer 1

8

Binary subtype 3 is reserved for UUID, which has a "strict" 16 byte length ( 32 string elements in hex notation ). Hence the error you are getting in your Java code.

The MongoDB shell does not have this "strict" typing, and as such both allows the creation and reading of the data. Nor is MongoDB itself "strictly typed", so as far as the engine is concerned it's just BSON Type 5, and does not look at it further.

If you inserted documents either use the correct data for the subtype:

{ "b": BinData(3,"ASNFZ4mrze/+3LqYdlQyEA==") }

Or a corrected subtype suiting the data, such a 0:

{ "b": BinDta(0,"abcdefgh") }

Then the Java driver has no problem when marshalling into it's Binary type.

So you get the error because your "data" is "invalid". Correct the data and there is no problem.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, great explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.