I have a large json document that I am trying to import into Mongo using C#.
My file that I create the document with currently creates the document as one long string.
As a one line string, there are 7126 characters. If I convert it to a json array it will be 387 lines.
When I try to import it as a one line document it errors out with
A first chance exception of type 'System.InvalidOperationException' occurred in MongoDB.Bson.dll
An unhandled exception of type 'System.InvalidOperationException' occurred in MongoDB.Bson.dll
Additional information: Duplicate element name 'Violation'.I am parsing the data with:
System.IO.StreamReader file = new System.IO.StreamReader(fileName);
line = file.ReadToEnd();
var bsonDoc = BsonDocument.Parse(line);
insertDoc(bsonDoc, collection);The 'duplicate' element name is a valid element in my document. Direct import into mongo using the command line creates no problems. If I process the document as a json array, it has not problem with the import through C#.
Is there a different way that I should be parsing the document as it comes in so that it can distinguish the objects inside?
{ "name": "Bob Hope", "age": 21, "gender": "Male" }
using System;
using MongoDB.Bson;
using MongoDB.Driver;
namespace ReadJSONIntoMongoDB
{
class MainClass
{
public static void Main (string[] args)
{
var connectionString = "mongodb://localhost";
var client = new MongoClient(connectionString);
var server = client.GetServer();
var database = server.GetDatabase("test");
var collection = database.GetCollection<BsonDocument>("bson_import");
string text = System.IO.File.ReadAllText(@"foo.txt");
var bsonDoc = BsonDocument.Parse (text);
collection.Insert (bsonDoc);
}
}
}
[ { "ContextId": "Vehicle", "ReportNumbers": { "values": [""10000000", "10000001", "10000002""] }, "RelatedTo": { "values": [] }, "DomainObjects": { "values": [] }, "Id": "z5agy1eu-zbkv-5sne-rhg6-ammteeg8sri2" },{ "ContextId": "Violation", "ReportNumbers": { "values": ["10000000"] }, "RelatedTo": { "values": ["10000001", "10000002"] }, "DomainObjects": { "values": [] }, "Id": "z2ax1bf7-qr8z-tatb-pwf8-v3158vw5op47" },{ "ContextId": "Violation", "ReportNumbers": { "values": ["10000001"] }, "RelatedTo": { "values": ["10000000", "10000002"] }, "DomainObjects": { "values": [] }, "Id": "7sgiaogk-4obg-yg5r-bg2r-dgekccy388f6" },{ "ContextId": "Violation", "ReportNumbers": { "values": ["10000002"] }, "RelatedTo": { "values": ["10000000", "10000001"] }, "DomainObjects": { "values": [] }, "Id": "bgbmnnfz-63y8-k7pi-tmii-c5c68y8m7ciu" } ]
public static void insertNewDocFromFile(string fileName, MongoCollection<BsonDocument> collection)
{
//read file into string and parse to BSON Document. Add document to collection
string line;
System.IO.StreamReader file = new System.IO.StreamReader(fileName);
line = file.ReadToEnd();
BsonDocument bsonDoc = new BsonDocument(true);
bsonDoc = convertStringToDoc(line);
collection.Insert(bsonDoc);
}