1

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. 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);  
                    }
TropicalViking
  • 407
  • 2
  • 9
  • 25

1 Answers1

0

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);
        }
    }
}
Dĵ ΝιΓΞΗΛψΚ
  • 5,068
  • 3
  • 13
  • 26
  • @TropicalViking still works: https://ibb.co/3W5Hcs3 other than the duplicated Id, the above code is working. are you sure you're connecting to the correct server/db/collection combo with your mongoclient? also, if you set a breakpoint after deserializing and inspect, does the `doc` variable contain the deserialized bsondocuments? – Dĵ ΝιΓΞΗΛψΚ Sep 29 '19 at 15:31