1

我正在研究一种异步读取 json 文件(包含 json 对象数组)内容并将其插入 mongodb 集合的方法,但我无法弄清楚问题所在。调试的时候没有报错,但是我的收藏还是空的。

 public async void InsertDocumentsInCollection(string File)
                    {
                        string text = System.IO.File.ReadAllText(File);
                        IEnumerable<BsonDocument> doc = BsonSerializer.Deserialize<BsonArray>(text).Select(p => p.AsBsonDocument);
            //Name of the collection is Cars
                        var collection = _database.GetCollection<BsonDocument>("Cars");
                        await collection.InsertManyAsync(doc);  
                    }
4

1 回答 1

0

我试图用以下方法重现这个问题,但它工作得很好。可能是文本文件的内容有问题。你可以发布文件的样本吗?

using MongoDB.Bson;
using MongoDB.Bson.Serialization;
using MongoDB.Driver;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace StackOverflow
{
    public class Program
    {
        private static async Task Main(string[] args)
        {
            var content = File.ReadAllText("E:\\Downloads\\cars.txt"); //https://mongoplayground.net/p/LY0W7vjDuvp

            var docs = BsonSerializer.Deserialize<BsonArray>(content).Select(p => p.AsBsonDocument);

            var collection = new MongoClient("mongodb://localhost")
                                    .GetDatabase("test")
                                    .GetCollection<BsonDocument>("Cars");

            await collection.InsertManyAsync(docs);
        }
    }
}
于 2019-09-29T14:05:25.187 回答