0
点赞
收藏
分享

微信扫一扫

C#简单操作MongoDB

热爱生活的我一雷广琴 2022-02-19 阅读 56
c#mongodb

新建一个窗体程序;使用Nuget安装mongodb.driver;或者直接引用dll如下;

代码;

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MongoDB.Bson;
using MongoDB.Driver;

namespace mgtest
{
    public partial class Form1 : Form
    {
        protected static IMongoDatabase _database;
        protected static IMongoClient _client;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            const string collectionName = "村子";
            string strCon = "mongodb://127.0.0.1:27017/mymgtest";
            var mongoUrl = new MongoUrlBuilder(strCon);
            string databaseName = mongoUrl.DatabaseName;
            _client = new MongoClient(mongoUrl.ToMongoUrl());
            _database = _client.GetDatabase(databaseName);

            var collection = _database.GetCollection<BsonDocument>(collectionName);
            var filter = new BsonDocument();

            var list = Task.Run(async () => await collection.Find(filter).ToListAsync()).Result;

            list.ForEach(p =>
            {
                textBox1.Text = textBox1.Text + p["name"].ToString() + "," + p["人数"].ToString() + "," + p["位置"].ToString() + Environment.NewLine;
            });
        }
    }
}

输出如下; 

 

这是前文创建的mongodb数据库;

 

举报

相关推荐

0 条评论