简体   繁体   English

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

[英]How can I save entire MongoDB collection to json/bson file using C#?

I have process, which first, generates lots of data which is save into mongoDB collection, then data is analyzed, and last - I want to save the whole collection to file on disk, and erase the collection. 我有进程,首先,生成大量数据,保存到mongoDB集合,然后分析数据,最后 - 我想将整个集合保存到磁盘上的文件,并擦除集合。 I know I could do it easily with MongoDump.exe, but I was wondering is there any way to do it directly from c#? 我知道我可以用MongoDump.exe轻松完成,但我想知道有没有办法直接从c#中做到这一点? - I mean not running console precess with - but using some functionality that is inside MOngo C# driver. - 我的意思是不使用控制台进程 - 但使用MOngo C#驱动程序内部的一些功能。

And, if it can be done - how would I do the reverse operation in c# ? 并且,如果可以这样做 - 我将如何在c#中执行反向操作? - namely: loading .bson file into collection? - 即:将.bson文件加载到集合中?

You can use C# BinaryFormatter to serialize object graph to disk. 您可以使用C#BinaryFormatter将对象图序列化为磁盘。 Also you can deserialize back to object graph. 您也可以反序列化回对象图。

Serialize: https://msdn.microsoft.com/en-us/library/c5sbs8z9%28v=VS.110%29.aspx 序列化: https//msdn.microsoft.com/en-us/library/c5sbs8z9%28v=VS.110%29.aspx

Deserialize: https://msdn.microsoft.com/en-us/library/b85344hz%28v=vs.110%29.aspx 反序列化: https//msdn.microsoft.com/en-us/library/b85344hz%28v=vs.110%29.aspx

However that is not mongodb or C# driver feature. 但是,这不是mongodb或C#驱动程序功能。

After serializing you can use the driver to drop the collection. 序列化后,您可以使用驱动程序删除集合。 And after deserializing you can use the driver to insert objects into a new collection. 反序列化后,您可以使用驱动程序将对象插入到新集合中。

Based on your rules, you may want to do some locking on that collection at the time you are doing the export process before you drop it. 根据您的规则,您可能希望在执行导出过程之前对该集合执行某些锁定,然后再将其删除。

Here's two methods that you can use to accomplish this: 您可以使用以下两种方法来完成此任务:

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));
        }
    }
}

And here's an example of how you would use them: 以下是您将如何使用它们的示例:

// 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();

Note that this code was written using version 2.0 of the MongoDB C# driver, which you can obtain via Nuget . 请注意,此代码是使用MongoDB C#驱动程序的2.0版编写的,您可以通过Nuget获取该驱动程序。 Also, the file reading code in the LoadCollectionFromFile method was obtained from this answer . 此外, LoadCollectionFromFile方法中的文件读取代码是从此答案中获得的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM