【问题标题】:not able to save documents in mongodb c# with .Net driver 2.0无法使用 .Net 驱动程序 2.0 在 mongodb c# 中保存文档
【发布时间】:2015-09-30 08:54:08
【问题描述】:

我想将文档保存在一个集合中,我的方法如下,但它根本不保存。

internal static void InitializeDb()
    {
        var db = GetConnection();
        var collection = db.GetCollection<BsonDocument>("locations");
        var locations = new List<BsonDocument>();
        var json = JObject.Parse(File.ReadAllText(@"..\..\test_files\TestData.json"));
        foreach (var d in json["locations"])
        {
            using (var jsonReader = new JsonReader(d.ToString()))
            {
                var context = BsonDeserializationContext.CreateRoot(jsonReader);
                var document = collection.DocumentSerializer.Deserialize(context);
                locations.Add(document);
            }
        }
        collection.InsertManyAsync(locations);
    }

如果我做了 async 和 await 然后它最近运行,我需要先运行它,然后只测试数据。

【问题讨论】:

  • 您必须等待“InsertManyAsync”方法。

标签: mongodb c#-4.0 bson


【解决方案1】:

供将来参考,异步方法末尾的wait() 像同步一样工作

internal static void InitializeDb()
{
    var db = GetConnection();
    var collection = db.GetCollection<BsonDocument>("locations");
    var locations = new List<BsonDocument>();
    var json = JObject.Parse(File.ReadAllText(@"..\..\test_files\TestData.json"));
    foreach (var d in json["locations"])
    {
        using (var jsonReader = new JsonReader(d.ToString()))
        {
            var context = BsonDeserializationContext.CreateRoot(jsonReader);
            var document = collection.DocumentSerializer.Deserialize(context);
            locations.Add(document);
        }
    }
    collection.InsertManyAsync(locations).wait();
}

【讨论】:

    猜你喜欢
    • 2015-06-25
    • 2011-11-19
    • 2015-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    相关资源
    最近更新 更多