C#中使用1.7版本驱动操作MongoDB简单例子

2019-12-26 11:21:44王旭

 

c#司机有一个连接池使用连接到服务器 效率。 不需要电话 连接 或 断开 ; 让司机照顾连接(调用 连接 是无害的,但是打电话呢 断开 是不好的,因为它关闭 连接池中的连接)。
完整的示例程序

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

 

using MongoDB.Bson;
using MongoDB.Driver;
using MongoDB.Driver.Builders;

namespace ConsoleApplication1
{
    public class Entity
    {
        public ObjectId Id { get; set; }
        public string Name { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var connectionString = "mongodb://localhost";
            var client = new MongoClient(connectionString);
            var server = client.GetServer();
            var database = server.GetDatabase("test");
            var collection = database.GetCollection<Entity>("entities");

            var entity = new Entity { Name = "Tom" };
            collection.Insert(entity);
            var id = entity.Id;

            var query = Query<Entity>.EQ(e => e.Id, id);
            entity = collection.FindOne(query);

            entity.Name = "Dick";
            collection.Save(entity);