将BSON文档写入文件

时间:2016-03-16 12:54:53

标签: c# mongodb

如何将集合中的所有数据写入外部文本文件?以下是集合:

[bp+di]

1 个答案:

答案 0 :(得分:0)

好吧,我想你想以json格式保存你的收藏。如果是这种情况,你可以这样做:

var r = collection.Find(new BsonDocument()).ToList();// Load all documents of that collection
System.IO.File.WriteAllText("file.txt",// path where you want to save the result
                             r.Aggregate<BsonDocument,string>("",(seed,document)=>seed+document.ToString()+"\n"));

如果您的收藏集包含大量文档,则出于效果原因,您可能会考虑使用StringBuilder

StringBuilder builder = new StringBuilder();
r.ForEach(d => builder.Append(d.ToString()+"\n"));
File.WriteAllText("file.txt",// path where you want to save the result
                  builder.ToString());