MongoDB学习笔记三一C#操作数据库

目标:向数据库插入两条Notes,一个包含标签一个没有,然后通过Update给不包含标签的Notes添加标签

    为了完成我们的目标,首先我们的到http://github.com/samus/mongodb-csharp 下载Mongodb的c#驱动,解压缩并打开Visual Studio解决方案,然后编译得到两个DLL的:MongoDB.Driver.dll、MongoDB.Linq.dll 。我们用json.net来实现序列化和反序列化,您可以从这里下载 。

    接着我们用vs2010创建一个简单的控制台应用程序,这里提供三种用C#操作MongoDB的方法:1.使用JSON 2.使用序列化/反序列化的Json.Net 3.使用动态代理

  一、这里我们创建一个帮助类(MongoJson.cs)来实现数据库Document和C# 实体类之间的映射:

using System.Collections.Generic;
using System.Linq;
using MongoDB.Driver;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Pls.MdbIntro
{
    public class MongoJson
    {
        private const string _oidContainerName = "_id";

        public T ObjectFrom<T>(Document document)
            where T : class, IMongoEntity
        {
            if (document == null)
                return null;

            return JsonConvert.DeserializeObject<T>(document.ToString());
        }

        public Document DocumentFrom(string json)
        {
            return PopulateDocumentFrom(new Document(), json);
        }

        public Document DocumentFrom<T>(T item)
            where T : class, IMongoEntity
        {
            return PopulateDocumentFrom(new Document(), item);
        }

        public Document PopulateDocumentFrom<T>(Document document, T item)
            where T : class, IMongoEntity
        {
            if (item == null)
                return document;

            var json = JsonConvert.SerializeObject(item, Formatting.None);

            return PopulateDocumentFrom(document, json);
        }

        private Document PopulateDocumentFrom(Document document, string json)
        {
            var keyValues = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);

            foreach (var keyValue in keyValues)
            {
                var isEmptyKeyField = (
                                          keyValue.Key == _oidContainerName && document[_oidContainerName] != MongoDBNull.Value);

                if (isEmptyKeyField)
                    continue;

                var value = keyValue.Value ?? MongoDBNull.Value;

                if (value != MongoDBNull.Value)
                {
                    var arrayValue = (keyValue.Value as JArray);
                    if (arrayValue != null)
                        value = arrayValue.Select(j => (string)j).ToArray();
                }

                if (document.Contains(keyValue.Key))
                    document[keyValue.Key] = value;
                else
                {
                    if (value != MongoDBNull.Value)
                        document.Add(keyValue.Key, value);
                }
            }

            return document;
        }
    }
}

二、创建Note实体类

    public interface IMongoEntity
    {
        string _id { get; set; }
        Oid GetOid();

        Document GetAsDocument();
        void UpdateFromDocument(Document document);
    }



  [Serializable]
    public class Note
        : IMongoEntity
    {
        public virtual string _id { get; set; }
        public virtual string Title { get; set; }
        public virtual string Body { get; set; }
        public virtual string[] Tags { get; set; }

        public virtual Oid GetOid()
        {
            return new Oid(_id);
        }

        public virtual Document GetAsDocument()
        {
            throw new NotImplementedException();
        }

        public virtual void UpdateFromDocument(Document document)
        {
            throw new NotImplementedException();
        }
    }

三、编写测试代码

            var json = new MongoJson();
            var mongo = new Mongo();

            mongo.Connect();

          
            var db = mongo["SimpleNotes"];
            db.SendCommand("dropDatabase");
            var notes = db["Notes"];

            PrintNotes("Initial notes", notes);

            //创建一个包含Tags的Note
            var firstNoteDocument = json.DocumentFrom("{Title : \"First note using Json.\",         Body : \"Some nice text.\", Tags : [\"MongoDB\", \"Getting started\"]}");
            notes.Insert(firstNoteDocument);



           //创建不包含Tags的Note
            var secondNoteDocument = json.DocumentFrom("{Title : \"Second note using Json.\", Body : \"Some nice text.\"}");
            notes.Insert(secondNoteDocument);



           //查询Tags为空的Note并更新添加Tags
            var noteDocument = notes.FindOne(new Document { { "Tags", MongoDBNull.Value } });
            noteDocument.Update(json.DocumentFrom("{Tags : [\"The tag\"]}"));

            notes.Update(noteDocument);

          

            mongo.Disconnect();


你可能感兴趣的:(mongodb)