自学内容网 自学内容网

C# 增删改查Mongo数据库的窗体

C# 增删改查Mongo数据库的窗体

using System;
using System.Windows.Forms;
using MongoDB.Driver;
using MongoDB.Bson;
 
public partial class MainForm : Form
{
    private IMongoCollection<BsonDocument> collection;
 
    public MainForm()
    {
        InitializeComponent();
        var client = new MongoClient("mongodb://localhost:27017");
        var database = client.GetDatabase("testdb");
        collection = database.GetCollection<BsonDocument>("testcollection");
    }
 
    private void btnInsert_Click(object sender, EventArgs e)
    {
        var document = new BsonDocument { { "name", txtName.Text }, { "value", txtValue.Text } };
        collection.InsertOne(document);
        MessageBox.Show("Inserted Successfully");
    }
 
    private void btnDelete_Click(object sender, EventArgs e)
    {
        var filter = Builders<BsonDocument>.Filter.Eq("name", txtName.Text);
        collection.DeleteOne(filter);
        MessageBox.Show("Deleted Successfully");
    }
 
    private void btnUpdate_Click(object sender, EventArgs e)
    {
        var filter = Builders<BsonDocument>.Filter.Eq("name", txtName.Text);
        var update = Builders<BsonDocument>.Update.Set("value", txtValue.Text);
        collection.UpdateOne(filter, update);
        MessageBox.Show("Updated Successfully");
    }
 
    private void btnRead_Click(object sender, EventArgs e)
    {
        var filter = Builders<BsonDocument>.Filter.Eq("name", txtName.Text);
        var result = collection.Find(filter).FirstOrDefault();
        if (result != null)
        {
            txtValue.Text = result["value"].AsString;
            MessageBox.Show("Read Successfully");
        }
        else
        {
            MessageBox.Show("No record found");
        }
    }
}


原文地址:https://blog.csdn.net/weixin_43050480/article/details/144344932

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!