cuốn sách gpt4 ai đã làm

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

In lại Tác giả: Vũ trụ không gian Thời gian cập nhật: 2023-11-03 15:30:11 27 4
mua khóa gpt4 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(json);

var collection = db.GetCollection("data");
await collection.InsertOneAsync(document);

我用要插入 mongodb 的数据创建了一个数组列表,我尝试创建一个 json 并使用 InsertOneAsync 方法插入它,但出现反序列化错误。可能有更简单的方法来执行此操作,但我不知道如何操作。

我尝试了一些关于此主题的其他 stackoverflow 线程,但无济于事。

"Cannot deserialize a 'BsonDocument' from BsonType 'Array'"

câu trả lời hay nhất

您甚至可能不必创建 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" }

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

27 4 0
không gian vũ trụ
Hồ sơ

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá taxi Didi miễn phí
Phiếu giảm giá taxi Didi
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress