[英]Insert json file containing an array of json documents into ammongodb collection using BsonDocument BsonArray
I am working on a method to asynchronously read the contents of a json file ( containing an array of json objects) and insert it into a mongodb collection but I cannot figure out what the issue is.我正在研究一种异步读取 json 文件(包含 json 对象数组)内容并将其插入 mongodb 集合的方法,但我不知道是什么问题。 There is no error when debugging, but my collection is still empty.
调试的时候没有报错,但是我的收藏还是空的。
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);
}
i tried to reproduce the issue with the following, but it works just fine.我试图用以下方法重现这个问题,但它工作得很好。 maybe it's something wrong with the contents of the text file.
可能是文本文件的内容有问题。 can you post a sample of the file?
你可以发布文件的样本吗?
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);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.