MongoDb在C#中的简单使用


  • Lv 1

    C#操作Mongodb实现简单的插入功能

    代码如下:

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Text;

    using System.Runtime.Serialization;

    using System.Data;

    using System.Data.SqlClient;

    using MongoDB.Bson;

    using MongoDB.Driver;

    namespace ConsoleApplication1

    {

        class Program

        {

            static void Main(string[] args)

            {

                //连接信息

                string conn = "mongodb://localhost";

                string database = "demoBase";

                string collection = "demoCollection";

                MongoServer mongodb = MongoServer.Create(conn);//连接数据库            

                MongoDatabase mongoDataBase = mongodb.GetDatabase(database);//选择数据库名            

               MongoCollection mongoCollection = mongoDataBase.GetCollection(collection);//选择集合,相当于表

                mongodb.Connect();

                //普通插入           

              var o = new { UserCode= 001, Name = "f10000", PassWord = "1qaz" };

                mongoCollection.Insert(o);

                //对象插入           

              Person p = new Person { UserCode= 002, Name = "f20000", PassWord = "2wsx" };

                mongoCollection.Insert(p);

                //BsonDocument 插入            

                BsonDocument b = new BsonDocument();

                b.Add("UserCode", 003);

                b.Add("Name", "f30000");

                b.Add("PassWord", "3edc");

                mongoCollection.Insert(b);

                Console.ReadLine();

            }

        }

        class Person {

            public string UserCode;

            public string Name;

            public string PassWord;

        }

    }


登录后回复
 

与 萌阔论坛 的连接断开,我们正在尝试重连,请耐心等待