I’ve tried every combination to import binary data for Mongo and I CANNOT get it to work. I’ve tried using new BinData(0, <bindata>) and I’ve tried using
{
"$binary" : "<bindata>",
"$type" : "0"
}
The first one gives me a parsing error. The second gives me an error reading “Invalid use of a reserved field name.”
I can import other objects fine. For reference, I’m trying to import a BASE64-encoded image string. Here is my current version of the JSON I’m using:
{"_id" : "72984ce4-de03-407f-8911-e7b03f0fec26","OriginalWidth" : 73, "OriginalHeight" : 150, { "$binary" : "", "$type" : "0" }, "ContentType" : "image/jpeg", "Name" : "test.jpg", "Type" : "5ade8812-e64a-4c64-9e23-b3aa7722cfaa"}
I actually figured out this problem and thought I’d come back to SO to help anyone out who might be struggling.
Essentially, what I was doing was using C# to generate a JSON file. That file was used on an import script that ran and brought in all kinds of data. One of the fields in a collection required storing binary image data as a Base64-encoded string. The Mongo docs (Import Export Tools and Importing Interesting Types) were helpful, but only to a certain point.
To format the JSON properly for this, I had to use the following C# snippet to get an image file as a byte array and dump it into a string. There is a more efficient way of doing this for larger strings (
StringBuilderfor starters), but I’m simplifying for the purpose of illustrating the example:I kept on failing on the type part, by the way. It translates to generic binary data is specified in the BSON spec here: http://bsonspec.org/#/specification.
If you want to skip straight to the JSON, the above code output a string very similar to this:
Then, I just used the
mongoimporttool to process the resulting JSON.Note: since I’m already in C#, I could’ve just used the Mongo DLL and done processing there, but for this particular case, I had to create the JSON files raw in the code. Fun times.