Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.6 kB
1
Indexable
Never
using System;
using System.IO;
using System.Threading.Tasks;
using MongoDB.Driver;
using MongoDB.Bson;
using MongoDB.Driver.GridFS;

namespace MongoDBMigration
{
    class Program
    {
        static async Task Main(string[] args)
        {
            var client = new MongoClient("mongodb://user:password@server:27017");
            var database = client.GetDatabase("sourceDB");
            var collection = database.GetCollection<BsonDocument>("source");
            var gridFsBucket = new GridFSBucket(database);

            var filter = Builders<BsonDocument>.Filter.Empty; // Filter all documents

            using (var cursor = await collection.FindAsync(filter))
            {
                while (await cursor.MoveNextAsync())
                {
                    foreach (var document in cursor.Current)
                    {
                        // Create a new GridFS file with the document's contents
                        using (var fileStream = new MemoryStream())
                        {
                            using (var writer = new StreamWriter(fileStream, leaveOpen: true))
                            {
                                await writer.WriteAsync(document.ToJson());
                                await writer.FlushAsync();
                            }
                            fileStream.Seek(0, SeekOrigin.Begin);
                            var fileInfo = await gridFsBucket.UploadFromStreamAsync(document["_id"].ToString(), fileStream);
                        }
                    }
                }
            }
        }
    }
}