Abdullah Dogan
Abdullah Dogan

Reputation: 103

Mongodb GridFs with C++

I want to insert BSON object from C++ to mongodb gridfs. I cannot find useful doc. about c++ gridfs API. Can you give an example how to insert or update BSON object on gridfs structure in c++. Suppose that i have a collection given below;

{ "_id" : "123", "data" : [ { "C1" : "value1","C2" : "value1"}] }

How can i insert this as gridfs in mongodb? P.S.: I tried to insert data as collections, but i got error because the document exceeds the file size limit.(document to be inserted exceeds maxBsonObjectSize) E.g. in the document above, the "data" array has sometimes more than 500.000 rows and with more columns. Thanks in advance

Upvotes: 0

Views: 1719

Answers (1)

sfritter
sfritter

Reputation: 891

The MongoDB C++ driver has a class called GridFS that will allow you to insert documents into your gridded system. GridFS is designed to operate on things abstracted as files, it reads its input as a stream of bytes rather than as some structured thing like a BSON object. You could convert your large BSON objects into strings to store them:

GridFS grid = new GridFS(*client, "database_name");

const char data[] = myLargeBSONObj.toString();
BSONObj result = grid->storeFile(data, sizeof data, "filename");

Or, you can store your large objects in a file and stream them into GridFS instead:

BSONObj result = grid->storeFile("path/to/file", "filename");

GridFS will not allow you to update a file once it has been inserted into the system. There is no safe way within the defined API to allow updates without encountering race conditions. To "update" a GridFS file, you'll have to read it out of the system, alter it in your application, and re-insert it into GridFS as a new file. This is slow and tedious. If you need to perform updates, I suggest that you instead re-design your schema so that your documents are smaller than 16 MB.

Upvotes: 1

Related Questions