在MongoDB中使用自定义容器类

时间:2015-07-01 09:00:50

标签: c# .net mongodb

我想将自己的自定义容器插入到带有2.0驱动程序的MongoDB集合中。但是当我尝试这样做时,我看不到任何事情发生。

我有以下内容:

namespace ConsoleApplication2
{
    class Program
    {
        private static IMongoDatabase _database;

        static void Main(string[] args)
        {
            var dbClient = new MongoClient("mongodb://localhost");
            _database = dbClient.GetDatabase("Test");

            var demo = new DemoClass() { Adderss = "add", Name = "Test friend" };
            var collection = _database.GetCollection<DemoClass>("DemoClass");
            collection.InsertOneAsync(demo);
        }
    }

    [BsonDiscriminator(RootClass = true)]
    public class DemoClass
    {
        [BsonId]
        public object Id { get; set; }
        public string Adderss { get; set; }
        public string Name { get; set; }
    }
}

未创建集合,但mongod告诉我已建立连接。

2015-07-01T10:58:09.998+0200 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:50317 #11 (4 connections now open)
2015-07-01T10:58:10.178+0200 I NETWORK  [conn11] end connection 127.0.0.1:50317 (3 connections now open)

有关如何使其发挥作用的任何建议? 欢迎提供完整的例子。

1 个答案:

答案 0 :(得分:0)

您必须注册要使用的课程。 见这个例子:

using System;
using System.Collections.Generic;
using MongoDB.Bson.Serialization;
using MongoDB.Driver;

namespace ConsoleApplication2
{
    class Program
    {
        private static IMongoDatabase _database;

        static void Main(string[] args)
        {
            var dbClient = new MongoClient("mongodb://localhost");
            _database = dbClient.GetDatabase("Test");

            BsonClassMap.RegisterClassMap<DemoClass>(); //This class can be used
            MongoInsert();
            MongoGet();
        }

        static private void MongoInsert()
        {
            //Create an entity
            var person = new DemoClass
            {
                FirstName = "Jane",
                Age = 12,
                PetNames = new List<dynamic> { "Sherlock", "Watson" }
            };

            //Insert into db, and wait for it (wanted for this example)
            _database.GetCollection<dynamic>("people").InsertOneAsync(person).Wait();
        }

        static private void MongoGet()
        {
            var names = _database.GetCollection<DemoClass>("people")
                .Find(x => x.FirstName == "Jane")
                .SortBy(x => x.Age)
                .Project(x => x.FirstName + " " + x.LastName) //This is important for the foreach-loop
                .ToListAsync();

            //Write all found entities
            foreach (var name in names.Result)
            {
                Console.WriteLine(name);
            }
        }
    }

    public class DemoClass
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
        public List<dynamic> PetNames { get; set; }
    }
}