Silentbob
Silentbob

Reputation: 3065

Import JSON file into MongoDB

I have a MongoDB instance on a Virtual Machine and I can connect using Compass. I have manually uploaded a JSON file using command line on that virtual machine without issue. The import creates two documents and works as expected using the command line:

mongoimport --jsonArray --db Historian_ManyDocs --collection TagValues --file historianData1.json

The json has the following format in the historianData1.json file:

[
    {
      "tagname": "99CalcTrigger",
      "engunits": "",
      "value": "2",
      "quality": "Good NonSpecific",
      "timestamp": "2018-12-13T10:45:05Z"
    },
    {
      "tagname": "Blank",
      "engunits": "",
      "value": "0",
      "quality": "Good NonSpecific",
      "timestamp": "2018-12-13T10:45:00Z"
    }
]

I want to automate this process somewhat and I have been playing with c# to do this using the following code:

    string line;
    using (StreamReader reader = new StreamReader(@"C:\historianData1.json")){
        line = reader.ReadLine();
    }


    var client = new MongoClient("mongodb://mongoserverIP:27017");
    var database = client.GetDatabase("Historian_ManyDocs");
    dynamic array = Newtonsoft.Json.JsonConvert.DeserializeObject(line);
    foreach (var item in array)
    {
        var document = BsonSerializer.Deserialize<BsonDocument>(item);
        var collection = database.GetCollection<BsonDocument>("TagValues");
        await collection.InsertOneAsync(document);
    }

This errors with the following error on the var document line with the following error:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'The best overloaded method match for 'MongoDB.Bson.Serialization.BsonSerializer.Deserialize(MongoDB.Bson.BsonDocument, System.Action)' has some invalid arguments'

Can anyone offer some suggestions please as I have been on this for 4 hours now.

Upvotes: 0

Views: 1214

Answers (1)

Gy&#246;rgy Guly&#225;s
Gy&#246;rgy Guly&#225;s

Reputation: 1598

You have to insert a POCO class into MonngoDB, so please create it like this:

public class POCOData
{
  public string tagname;
  public string engunits;
  public string value;
  public string quality;
  public TimeOffset timestamp;
}

after you can use it in Deserialize:

foreach (var item in array)
{
    var document = BsonSerializer.Deserialize<POCOData>(item);
    var collection = database.GetCollection<BsonDocument>("TagValues");
    await collection.InsertOneAsync(document);
}

Upvotes: 1

Related Questions