gpt4 book ai didi

c# - 使用 C# 将数据插入 Mongodb

转载 作者:太空宇宙 更新时间:2023-11-03 15:30:11 26 4
gpt4 key购买 nike

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<BsonDocument>(json);

var collection = db.GetCollection<BsonDocument>("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<FooItem> 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<BsonDocument>("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" }

关于c# - 使用 C# 将数据插入 Mongodb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34032269/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com