如何使用 C# 将整个 MongoDB 集合保存到 json/bson 文件?

Mik*_*ike 4 c# json mongodb bson

我有一个流程,首先生成大量数据,并将其保存到 mongoDB 集合中,然后分析数据,最后 - 我想将整个集合保存到磁盘上的文件中,并删除该集合。我知道我可以使用 MongoDump.exe 轻松完成此操作,但我想知道是否有任何方法可以直接从 c# 完成此操作?- 我的意思是不运行控制台进程 - 而是使用 MOngo C# 驱动程序内部的一些功能。

而且,如果可以做到 - 我将如何在 C# 中进行反向操作?- 即:将 .bson 文件加载到集合中?

Don*_*nut 5

您可以使用以下两种方法来实现此目的:

public static async Task WriteCollectionToFile(IMongoDatabase database, string collectionName, string fileName)
{
    var collection = database.GetCollection<RawBsonDocument>(collectionName);

    // Make sure the file is empty before we start writing to it
    File.WriteAllText(fileName, string.Empty);

    using (var cursor = await collection.FindAsync(new BsonDocument()))
    {
        while (await cursor.MoveNextAsync())
        {
            var batch = cursor.Current;
            foreach (var document in batch)
            {
                File.AppendAllLines(fileName, new[] { document.ToString() });
            }
        }
    }
}

public static async Task LoadCollectionFromFile(IMongoDatabase database, string collectionName, string fileName)
{
    using (FileStream fs = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    using (BufferedStream bs = new BufferedStream(fs))
    using (StreamReader sr = new StreamReader(bs))
    {
        var collection = database.GetCollection<BsonDocument>(collectionName);

        string line;
        while ((line = sr.ReadLine()) != null)
        {
            await collection.InsertOneAsync(BsonDocument.Parse(line));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

以下是如何使用它们的示例:

// Obviously you'll need to change all these values to your environment
var connectionString = "mongodb://localhost:27017";
var database = new MongoClient(connectionString).GetDatabase("database");
var fileName = @"C:\mongo_output.txt";
var collectionName = "collection name";

// This will save all of the documents in the file you specified
WriteCollectionToFile(database, collectionName, fileName).Wait();

// This will drop all of the documents in the collection
Task.Factory.StartNew(() => database.GetCollection(collectionName).DeleteManyAsync(new BsonDocument())).Wait();

// This will restore all the documents from the file you specified
LoadCollectionFromFile(database, collectionName, fileName).Wait();
Run Code Online (Sandbox Code Playgroud)

请注意,此代码是使用 MongoDB C# 驱动程序 2.0 版编写的,您可以通过Nuget获取该驱动程序。另外,该方法中的文件读取代码是从这个答案LoadCollectionFromFile中获取的。