MongoDB 学习记录

下载地址:

http://www.mongodb.org/downloads   根据不同系统下载对应版本

引用NuGet包:(ps:其实不需要这么多,自己测试时,安装了这么多~~)

构造Helper类:

using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebApiTest.Models;

namespace WebApiTest
{
    public class MongodbHelper
    {
        static public readonly MongodbHelper Instance = new MongodbHelper();
        private MongoDatabase db;

        public MongodbHelper()
        {
            //MongoDB连接地址,下面是本机地址
            string strconn = "mongodb://localhost:27017";
            //默认一个DataBase名称
            string dbName = "test";
            MongoDB.Driver.MongoClient mongoClient = new MongoClient(strconn);
            MongoServer server = mongoClient.GetServer();
            db = server.GetDatabase(dbName);
        }

        public MongoDatabase DB
        {
            get { return db; }
        }

        public MongoCollection this[string value]
        {
            get
            {
                return db.GetCollection(value);
            }
        }
    }
}

调用:这里用的是WebApi,做了个增、改、删、查的操作

新增:初始化100w条数据

// POST api/values
        public void Post([FromBody]string value)
        {
            MongodbHelper mongodbHelper = new MongodbHelper();
            var contactsList = mongodbHelper.DB.GetCollection("Contact");
            WriteConcernResult result;

            for (int i = 0; i < 1000000; i++)
            {
                Contact contact = new Contact();
                contact.Id = ObjectId.GenerateNewId().ToString();
                contact.Name = "张三" + i;
                contact.Phone = "15012345678";
                contact.Email = "qqq@qq.com";
                contact.LastModified = System.DateTime.Now;
                result = contactsList.Insert<Contact>(contact);

                bool hasError = result.HasLastErrorMessage;
            }


        }

修改:

// PUT api/values/5
        public void Put(string id)
        {
            MongodbHelper mongodbHelper = new MongodbHelper();
            var contacts = mongodbHelper.DB.GetCollection("Contact");
            Contact contact = new Contact();
            contact.Id = id;
            contact.Name = "李四";
            BsonDocument bd = BsonExtensionMethods.ToBsonDocument(contact);
            IMongoQuery query = Query.EQ("_id", contact.Id);
            contacts.Update(query, new UpdateDocument(bd));
        }

删除:

// DELETE api/values/5
        public void Delete(string id)
        {
            try
            {
                MongodbHelper mongodbHelper = new MongodbHelper();
                var contacts = mongodbHelper.DB.GetCollection("Contact");
                //这个写法是错误的,会删除不了数据
                //var query = new QueryDocument { { "_id", ObjectId.Parse(id) } };
                //contactsList.Remove(query);

                //正确写法
                IMongoQuery query = Query.EQ("_id", id);
                contacts.Remove(query);
            }
            catch (Exception ex)
            {

                throw;
            }

        }

查询:

// GET api/values
        public IEnumerable<Contact> Get()
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            List<Contact> model = new List<Contact>();
            MongodbHelper mongodbHelper = new MongodbHelper();
            var contactList = mongodbHelper.DB.GetCollection("Contact").FindAll().AsEnumerable();
            model = (from contact in contactList
                     select new Contact
                     {
                         Id = contact["_id"].AsString,
                         Name = contact["Name"].AsString,
                         Phone = contact["Phone"].AsString,
                         Email = contact["Email"].AsString,
                         LastModified = contact["LastModified"].AsDateTime
                     }).ToList();
            stopwatch.Stop();
            long time = stopwatch.ElapsedMilliseconds;
            return model;
        }

前台AJax调用:

<script src="~/Scripts/jquery-3.3.1.js"></script>
<script type="text/javascript">
    $(function () {
        $("#btnInsert").click(function () {
            $.ajax({
                type: "POST",
                url: "/api/values/Post",
                data: {},
                async: false,
                success: function (data) {

                }
            });

        });

        $("#btnUpdate").click(function () {
            var id = "5b878b337562c84274ac262a";
            $.ajax({
                type: "Put",
                url: "/api/values/" + id,
                async: false,
                success: function (data) {

                }
            });

        });

        $("#btnDel").click(function () {
            var id = "5b878b337562c84274ac2628";
            $.ajax({
                type: "Delete",
                url: "/api/values/" + id,
                async: false,
                success: function (data) {

                }
            });

        });
    });

</script>

<div class="jumbotron">
    <h1>ASP.NET</h1>

    <input type="button" value="新增数据" id="btnInsert" /> <br /> <br />

    <input type="button" value="修改数据" id="btnUpdate" /> <br /> <br />

    <input type="button" value="删除数据" id="btnDel" />

    <p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS, and JavaScript.</p>
    <p><a href="https://asp.net" class="btn btn-primary btn-lg">Learn more &raquo;</a></p>
</div>

源代码下载:开发环境  VS2017

链接: https://pan.baidu.com/s/1BMKTSdKW5srB0DKiQvkmuw 密码: csyx

原文地址:https://www.cnblogs.com/luyiwei/p/9561241.html