using MongoDB.Bson;
using MongoDB.Driver;
protected static IMongoClient client;
protected static IMongoDatabase db;
public async void Insert()
{
client = new MongoClient();
db = client.GetDatabase("Database");
string json = "[";
foreach (CsvObjects.Connections e in connectionsList)
{
json += "{";
json += "\"DateTime\":\"" + e.DateTime + "\",";
json += "\"Value\":\"" + e.Value + "\",";
json += "},";
}
json += "]";
MongoDB.Bson.BsonDocument document = MongoDB.Bson.Serialization.BsonSerializer.Deserialize(json);
var collection = db.GetCollection("data");
await collection.InsertOneAsync(document);
我用要插入 mongodb 的数据创建了一个数组列表,我尝试创建一个 json 并使用 InsertOneAsync 方法插入它,但出现反序列化错误。可能有更简单的方法来执行此操作,但我不知道如何操作。
我尝试了一些关于此主题的其他 stackoverflow 线程,但无济于事。
"Cannot deserialize a 'BsonDocument' from BsonType 'Array'"
您甚至可能不必创建 JSON 字符串,除了冗长之外它容易出错。例如,您可以改用 MongoDB.Bson 中的 ToBsonDocument 扩展。
using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Example
{
class FooItem
{
public DateTime DateTime { get; set; }
public string Value { get; set; }
}
class InsertTest
{
protected static IMongoClient _client;
protected static IMongoDatabase _db;
static void Main(string[] args)
{
_client = new MongoClient();
_db = _client.GetDatabase("Database");
MainAsync(args).GetAwaiter().GetResult();
}
static IEnumerable GetList()
{
yield return new FooItem
{
DateTime = DateTime.Now,
Value = "I am foo 1"
};
yield return new FooItem
{
DateTime = DateTime.Now,
Value = "I am foo 2"
};
}
static async Task MainAsync(string[] args)
{
var collection = _db.GetCollection("data");
foreach (var item in GetList())
{
await collection.InsertOneAsync(item.ToBsonDocument());
}
}
}
}
这会产生这个结果
{ "_id" : ObjectId("565e70208af88628ecb3237d"), "DateTime" : ISODate("2015-12-02T04:14:24.789Z"), "Value" : "I am foo 1" }
{ "_id" : ObjectId("565e70228af88628ecb3237e"), "DateTime" : ISODate("2015-12-02T04:14:26.511Z"), "Value" : "I am foo 2" }
Tôi là một lập trình viên xuất sắc, rất giỏi!