Updating GridFS metadata using C#

1,657 views
Skip to first unread message

Neeraj Singh

unread,
Dec 7, 2016, 5:22:48 PM12/7/16
to mongodb-user
Hi,

I had spent considerable time trying to find a solution to update the metadata of a GridFS document but unable to succeed.
I am able to update the metabdata os mongo shell, but could not find relevant C# driver function to update GridFS metadata directly. 

Can someone please guide me in right direction by either sharing some C# code snippet or GridFSBucket API which can help me update the metadata.
Well, in my case i donl't wana replace the file, consider user just want to rename the file or add some tags, in these scenarios I would prefer updating metadata rather than deleting existing file and adding new file using the same id.

Thanks in advance. 

Wan Bachtiar

unread,
Dec 15, 2016, 12:57:21 AM12/15/16
to mongodb-user

Can someone please guide me in right direction by either sharing some C# code snippet or GridFSBucket API which can help me update the metadata.

Hi Neeraj,

GridFS is a specification for storing and retrieving files. Behind the scenes it uses two collections to store the files. One collection stores the file chunks and the other stores the file metadata. You can query and update GridFS metadata collection, by default lives in a collection named databaseName.fs.files

An example to update metadata value to new value for GridFS entry with filename equals to my_unique_filename:

IMongoDatabase database = client.GetDatabase("databaseName");
var grid_files_collection = database.GetCollection<BsonDocument>("fs.files");
var filter = Builders<BsonDocument>.Filter.Eq("filename", "my_unique_filename");
var update = Builders<BsonDocument>.Update.Set("metadata.my_metadata", "new value");

var result = grid_files_collection.UpdateOne(filter, update);
if (result.IsModifiedCountAvailable)
{
  Console.WriteLine(result.ModifiedCount);
}

The example snippet above uses the current stable C# driver v2.3.

To rename a file see GridFS: renaming a single file

For more information see also:

Regards,

Wan.

Reply all
Reply to author
Forward
0 new messages