C#简单操作MongoDB
Posted bcbobo21cn
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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数据库;
以上是关于C#简单操作MongoDB的主要内容,如果未能解决你的问题,请参考以下文章