如何在C中使用MongoDB ConventionPack#我有以下代码:

MongoDatabase Repository = Server.GetDatabase(RepoName);
this.Collection = Repository.GetCollection<T>(CollectionName);
var myConventions = new ConventionPack();
myConventions.Add(new CamelCaseElementNameConvention());

Does the convention pack automatically attach to this.Collection?
When I load in a new object will it automatically persist it as this case?
Do I have to add tags in my class declaration (like a data contract)?

推荐答案

您需要在ConventionRegistry中注册包装:

var pack = new ConventionPack();
pack.Add(new CamelCaseElementNameConvention());
ConventionRegistry.Register("camel case",
                            pack,
                            t => t.FullName.StartsWith("Your.Name.Space."));

如果你想在全局应用这个参数,你可以用类似于t => true的简单参数替换最后一个参数.

序列化和反序列化的工作示例代码(驱动程序1.8.20,mongodb 2.5.0):

using System;
using System.Linq;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Driver;

namespace playground
{
    class Simple
    {
        public ObjectId Id { get; set; }
        public String Name { get; set; }
        public int Counter { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            MongoClient client = new MongoClient("mongodb://localhost/test");
            var db = client.GetServer().GetDatabase("test");
            var collection = db.GetCollection<Simple>("Simple");
            var pack = new ConventionPack();
            pack.Add(new CamelCaseElementNameConvention());
            ConventionRegistry.Register("camel case", pack, t => true);
            collection.Insert(new Simple { Counter = 1234, Name = "John" });
            var all = collection.FindAll().ToList();
            Console.WriteLine("Name: " + all[0].Name);
        }
    }
}

Mongodb相关问答推荐

在MogoDB中按时间间隔分组、统计文档和获取间隔时间

MongoDB 聚合 groupBy 日期并计算子文档

如何使用 MindsDB 和 MQL(对于我的 MongoDB 实例)实施零样本分类?

Mongoose 更新不同类型的记录

如何过滤查找mongodb的结果

MongoDB查询仅返回嵌入文档

Mongodb 仅在值唯一时插入,否则更新 - 在 node.js 中

MongoDB C# 驱动程序 - 如何将 _id 存储为 ObjectId 但映射到字符串 Id 属性?

MongoDB 的 Java 语法

指定字段对于 MongoDB 是transient瞬态的,但对于 RestController 不是

返回从循环中调用的数据库查询中检索到的数据的问题

通过 Spring Boot 应用程序访问 mongodb 时的身份验证错误

将 mongoose 字符串模式类型默认值设为空白并使该字段可选

如何在任意深度查找 MongoDB 字段名称

为 php 5.6 (XAMPP) 添加 mongodb 扩展

适用于 Windows 10 64 位的 MongoDB 下载

RoR3 上的 Mongoid:1)如何在查询中返回特定字段? 2)需要什么 inverse_of ?

mongodb nodejs - 转换圆形 struct

如何使用 Pymongo 在 MongoDB 中 Select 单个字段?

Mongodb $lookup 使用 _id 无效果