在MongoDB中使用自定义容器类

本文关键字:自定义 容器类 MongoDB | 更新日期: 2023-09-27 18:00:33

我想用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)

有什么建议可以让它发挥作用吗?欢迎提供完整的例子。

在MongoDB中使用自定义容器类

您必须注册要使用的类。参见此示例:

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; }
    }
}