Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query for binary data - MongoDB

Tags:

java

mongodb

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.

like image 828
DistribuzioneGaussiana Avatar asked Mar 30 '16 10:03

DistribuzioneGaussiana


1 Answers

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.

like image 155
Blakes Seven Avatar answered Nov 10 '22 16:11

Blakes Seven