How to recover all the GridFs files in MongoDB?

4

I have saved files in Mongodb using GridFs and C # but now I need to recover ALL the files I have saved in my database and store them in a folder. I hope you can advise me a little. Thanks

This is the Code as I keep my files

var connectionString = "mongodb://localhost";
var client = new MongoClient(connectionString);
var server = client.GetServer();
var database = server.GetDatabase("data");
var gridFs = new MongoGridFs(database);

//Este es el archivo que subo a la Base
string ruta = "C:\files\rasta.jpeg";

//Esta parte hace el proceso de carga
      using (var file = File.OpenRead(ruta))
    {
        id = gridFs.AddFile(file, rute);                            
    }

So it shows me the files my Robomongo

What I need is to recover all the files that I have saved in my Base and store it in my "C: /" folder

How do I recover a file ??? I get the id of the last saved file and store it in a MemoryStream

     using (var file = gridFs.GetFile(id))
        {
            var buffer = new byte[file.Length];
            string sd = file.Read(buffer, 0, (int)file.Length).ToString();
            MemoryStream MS = new MemoryStream(buffer);
        }

Once the MemoryStream is obtained it is easy to save my file in my directory, what complicates me is to obtain ALL the files saved in the database and save them in my Folder.

In the bottom part I write how to solve my problem

    
asked by Rastalovely 22.11.2016 в 16:25
source

2 answers

2

Here, in the official documentation of MongoDB there is no method that returns all the files at once documentation . However, if you can save this information in a table you can use this solution:

Within your project c# you must create a class of the type of object that you keep in your database. Suppose your object has

Id, Name, Surname, image and your table is called Person.

You must create a class called Persona with the aforementioned attributes, then create.

var client = new MongoClient();
var db = client.GetDataBase("TuDB");
var coleccion = db.GetCollection<Persona>("Persona");

var objetos = coleccion.Select(p => p).ToListAsync().Result;
foreach (var objeto in objetos)
{
    Console.WriteLine(" Id: " + objeto.Id);
}

EDIT

I think that var objetos = coleccion.Select(p => p).ToListAsync().Result; is not necessary in this case when you do not need to filter for any particular field in your table. If you need all and without a filter you can run db.GetCollection<Persona>("Persona.Id"); Therefore, it could be like this:

var coleccion = db.GetCollection<Persona>("Persona");
foreach (var objeto in collecion)
{
    Console.WriteLine(" Id: " + objeto.Id);
}

Here you will have all the id, all the path of the images or whatever you want of your object and you can save them inside the folder you want. I do not leave the code to save them since you yourself said that it was easy for you to save with the id the object, inside the foreach you should save the images in your local folder.

To filter if you need it, it can be:

coleccion.Find(p => p.Nombre == 'Ejemplo').Limit(5).ToListAsync().Result;

Note:

To create the class quickly copy the JSON format that you get from your MongoDB, remove the words ObjectId , ISODate and then in Visual Studio in the Edit->Paste Special->Paste JSON As Classes tab and create your class, then you must change obviously the name of the class that is generated and the id that you have will create them as string , you must change them to ObjectId and add the dependence of MongoDB ObjectId

    
answered by 07.12.2016 / 14:05
source
2
  

This is the way I was able to solve my problem, I hope it will be   useful.

GridFs , allows to store large volume files in our database Mongo (music, videos, etc) these files are partitioned into arrays of 16 MB, automatically creates two Collection (tables) fs.files and fs.chunks .

To connect Mongodb with C# , you need a Driver which can be downloaded from Nuget Package of C# Mongocsharpdriver and add your assemblies.

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using MongoDB.Driver.GridFS;
using MongoDB.Driver.Linq;

How do I upload files to the database MongoDB ?

//Datos del Servidor
var connectionString = "mongodb://localhost";
var client = new MongoClient(connectionString);
var server = client.GetServer();
var database = server.GetDatabase("data");
var gridFs = new MongoGridFs(database);

//Este es el archivo que subo a la Base
string ruta = "C:\files\foto.jpeg";

//Esta parte hace el proceso de carga
  using (var file = File.OpenRead(ruta))
{
    id = gridFs.AddFile(file, rute);                            
}

How do I recover the file that has been loaded?

 using (var file = gridFs.GetFile(id))
    {
        var buffer = new byte[file.Length];
        string sd = file.Read(buffer, 0, (int)file.Length).ToString();
        MemoryStream MS = new MemoryStream(buffer);
        pictureBox.Image = Image.FromStream(MS); //Mostrar la Fotografia
    }

How do I recover all the files that have been uploaded?

protected static IMongoClient cliente = new MongoClient();
protected static IMongoDatabase data = cliente.GetDatabase("database");
var collection = data.GetCollection<BsonDocument>("fs.files");
var filtro = Builders<BsonDocument>.Filter.Empty;
var cursor = collection.Find(filtro);
var listado = cursor.ToList();
foreach (var item in listado)
   {
     string idfile = item["_id"].ToString();
     using (var file = gridFs.GetFile(ObjectId.Parse(idfile)))
       {
         var buffer = new byte[file.Length];
         string sd = file.Read(buffer, 0, (int)file.Length).ToString();
         //Guardo todos los archivos subidos a la base en la carpeta Fotografias
         FileStream fs = new FileStream(@"C:\Fotografias\" + idfile, FileMode.Create, FileAccess.Write);
         fs.Write(buffer, 0, (int)file.Length);
          fs.Close();
        }
   }
    
answered by 08.12.2016 в 16:36