What does the “0” mean in MongoDB's BinData(0, “e8MEnzZoFyMmD7WSHdNrFJyEk8M=”)?

StackOverflow https://stackoverflow.com/questions/9338989

  •  27-10-2019
  •  | 
  •  

Question

The MongoDB shell prints binary data as a Base64-encoded string wrapped in what looks like a function call:

"_id" : BinData(0,"e8MEnzZoFyMmD7WSHdNrFJyEk8M=")

What does the "0" mean?

Was it helpful?

Solution

http://docs.mongodb.org/manual/reference/mongodb-extended-json/#binary

The BSON BinData datatype is represented via class BinData in the shell. Run help misc for more information.

> new BinData(2, "1234")
BinData(2,"1234")

from the shell

help misc
b = new BinData(subtype,base64str)  create a BSON BinData value

The 0 in your case is the BSON subtype

http://bsonspec.org/#/specification

binary  ::=   int32 subtype (byte*)   Binary - The int32 is the number of bytes in the (byte*).
subtype ::=   "\x00"  Generic binary subtype
  |   "\x01"  Function
  |   "\x02"  Binary (Old)
  |   "\x03"  UUID (Old)
  |   "\x04"  UUID
  |   "\x05"  MD5
  |   "\x80"  User defined

Similar question on this thread

http://groups.google.com/group/mongodb-dev/browse_thread/thread/1965aa234aa3ef1e

OTHER TIPS

Macrolinux is right but you have to be careful with his example as it will work but by accident.

The first argument to BinData() is the BSON binary subtype which, as has been mentioned is one of the following:

generic:  \x00 (0)
function: \x01 (1)
old:      \x02 (2)
uuid_old: \x03 (3)
uuid:     \x04 (4)
md5:      \x05 (5)
user:     \x80 (128)

These are just helpers so that the deserializer can interpret the binary data differently depending on what those bytes represent except for the subtype 2 which is like the generic subtype but stores an int32 representing the length of the byte array as the first 4 bytes of data.

Now to see why the example is wrong you'll note that calling BinData(2, "1234") doesn't store the binary representing the string "1234" for two reasons:

  • The BinData function interprets that string as a base64 encoded string.
  • Type 2 would require that the first 4 bytes be an int32 containing the length of the byte array.

See bsonspec.org for more information.

I believe they they correspond to the BSON subtypes:

subtype ::= "\x00" Binary / Generic | "\x01" Function | "\x02" Binary (Old) | "\x03" UUID | "\x05" MD5 | "\x80" User defined

Looking at that, it appears that 0 is almost always a valid choice.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top