今朝有幸尝芒果,发现自增长ID类型有多种,唯独没有Long/Int。

一思路:
1. 自建一个Collection(表,假设名为:IdentityEntity,其中字段:_id, Key, Value,其中_id你懂的,Key:Collection名,需要用Long/Int自增长主键的Collection名,value:Key字段中所存Collection的Long/Int自增长最大值),此表用于存入要用Long/Int自增长主键的Collection信息(为方便举例:XLogs)
结构自建的Collection, IdentityEntity如下:
_id        Key      Value
new Guid()    XLogs      5

2. 每次往XLogs新增数据时,将当前最大值(5)取出来,然后再加1,我们知道自增长键是无需我们明确Insert的,当然它也一样整个过程都是由Mongo自身框架内部完成。

3. 既然是内部完成,我们就得实现一小部分代码,让Mongo框架来调用

二实现:

1. Mongo框架中的接口:IIdGenerator

 #region 程序集 MongoDB.Bson.dll, v1.9.2.235
// E:\Projects\DLL\MongoDB.Bson.dll
#endregion using System; namespace MongoDB.Bson.Serialization
{
// 摘要:
// An interface implemented by Id generators.
public interface IIdGenerator
{
// 摘要:
// Generates an Id for a document.
//
// 参数:
// container:
// The container of the document (will be a MongoCollection when called from
// the C# driver).
//
// document:
// The document.
//
// 返回结果:
// An Id.
object GenerateId(object container, object document);
//
// 摘要:
// Tests whether an Id is empty.
//
// 参数:
// id:
// The Id.
//
// 返回结果:
// True if the Id is empty.
bool IsEmpty(object id);
}
}

2. 实现接口,代码:

 public class LongIdGenerator<TDocument, TKey> : IIdGenerator where TDocument : class
{
private static LongIdGenerator<TDocument, TKey> _instance = new LongIdGenerator<TDocument, TKey>();
public static LongIdGenerator<TDocument, TKey> Instance { get { return _instance; } } public object GenerateId(object container, object document)
{
TKey id = default(TKey);
var collection = container as MongoCollection<TDocument>;
if (null != collection)
{
var mongoDB = collection.Database;
var idColl = mongoDB.GetCollection<IdentityEntity<TKey>>("IdentityEntity");
var keyName = document.GetType().Name;
id = RealGenerateId(idColl, keyName) ;
}
return id;
} private TKey RealGenerateId(MongoCollection<IdentityEntity<TKey>> idColl, string keyName)
{
TKey id;
var idQuery = new QueryDocument("Key", BsonValue.Create(keyName));
var idBuilder = new UpdateBuilder();
idBuilder.Inc("Value", ); var args = new FindAndModifyArgs();
args.Query = idQuery;
args.Update = idBuilder;
args.VersionReturned = FindAndModifyDocumentVersion.Modified;
args.Upsert = true; var result = idColl.FindAndModify(args);
if (!string.IsNullOrEmpty(result.ErrorMessage))
{
throw new Exception(result.ErrorMessage);
}
id = result.GetModifiedDocumentAs<IdentityEntity<TKey>>().Value;
return id;
} public bool IsEmpty(object id)
{
if (null == id)
{
return false;
}
return true;
}
}

2.2. 从上代码看我们知道,先要了解对Mongodb Collection的增,改,查等基本操作,然后理解“思路”中所提内容。注意Collection IdentityEntity在代码中已写死,当他不存在时第一次运行会自动新增此Collection。

三应用
到此已完成代码实现。即然实现,那么开始谈应用:
方式1.

  public class XLogs : BaseLog, IEntity<long>
{
//应用:在long自增长键上加此特性
[BsonId(IdGenerator = typeof(LongIdGenerator<XLogs>))]
public long Id { get; set; } public byte Status { get; set; } public string CreatedBy { get; set; } public System.DateTime CreatedDate { get; set; } public string Remark { get; set; } public decimal Amount { get; set; }
}

方式2. 注册的方式,在数据进Collection XLogs之前,就要运行它

 BsonClassMap.RegisterClassMap<XLogs>(rc =>
{
rc.AutoMap();
rc.SetIdMember(rc.GetMemberMap(c => c.Id));
rc.IdMemberMap.SetIdGenerator(LongIdGenerator<XLogs, long>.Instance);
});

MongoDB Long/Int(长整型)的自增长主键 解决方案的更多相关文章

  1. python基础知识2——基本的数据类型——整型,长整型,浮点型,字符串

    磨人的小妖精们啊!终于可以归置下自己的大脑啦,在这里我要把--整型,长整型,浮点型,字符串,列表,元组,字典,集合,这几个知识点特别多的东西,统一的捯饬捯饬,不然一直脑袋里面乱乱的. 对于Python ...

  2. Python基础:数值(布尔型、整型、长整型、浮点型、复数)

    一.概述 Python中的 数值类型(Numeric Types)共有5种:布尔型(bool).整型(int).长整型(long).浮点型(float)和复数(complex). 数值类型支持的主要操 ...

  3. Python基础:1.数据类型(空、布尔类型、整型、长整型、浮点型、字符串)

    提示:python版本2.7,windows系统 Python提供的基本数据类型:空.布尔类型.整型.长整型.浮点型.字符串.列表.元组.字典.日期 1.空(None) None,是一个特殊的值,不能 ...

  4. javascript没有长整型

    记录一下前几天踩坑的经历. 背景:一个项目某一版之后很多用easyui的表格控件treegrid渲染的表格都显示不出来了 奇怪的地方主要有以下几点: 项目在测试环境才会这样,在本机能够正常运行,多次重 ...

  5. PHP长整型在32位系统中强制转化溢出

    CleverCode近期遇到一个PHP项目整形转化问题,mysql有一个字段id是bigint的,里面有长整型,如id = 5147486396.可是php代码因为历史原因却部署在多台机器中,当中A机 ...

  6. 零基础如何学好Python 之int 数字整型类型 定义int()范围大小转换

    本文主题是讲python数字类型python int整型使用方法及技巧.它是不可变数据类型中的一种,它的一些性质和字符串是一样的,注意是整型不是整形哦. Python int有多种数字类型:整型int ...

  7. Mac地址转换成long长整型 2

    数据之间的转换可以使用   System.Convert Mac地址转换成long长整型 /// <summary> /// 解析长整形的数据使其转换为macID /// </sum ...

  8. Mac地址转换成long长整型

    Mac地址转换成long长整型 using System;using System.Collections.Generic;using System.IO;using System.Text;usin ...

  9. 整型,长整型,无符号整型等 大端和小端(Big endian and Little endian)

    一.大端和小端的问题 对于整型.长整型.无符号整型等数据类型,Big endian 认为第一个字节是最高位字节(按照从低地址到高地址的顺序存放数据的高位字节到低位字节):而 Little endian ...

随机推荐

  1. [原创] Web UI 自动化日期控件的处理

    序 在构建自动化套件的过程中,日期操作是一件很重要也很频繁的事情.有的日期控件的div层级结构复杂,同一个类型的日期控件在多个子系统中的表现形式也大相径庭.多数工程师为了避免重复的工作,会封装抽象一个 ...

  2. XML Schema验证

    XML Schema验证 一.什么事Schema(XSD) XML Schema是微软定义的一套用来验证XML技术.是一套预先规定的XML元素和属性创建的,这些元素和属性定义了XML文档的结构和内容模 ...

  3. PHP将解析xml变为数组方法

    最近想要做一个插件机制,需要用到xml,在解析xml时候需要转换为数组,特意记录一个此种解析方式 xml文件 <?xml version="1.0" encoding=&qu ...

  4. 以NameValueCollection 修改URL中的查询参数

    以NameValueCollection 修改URL中的查询参数 本文参考于:http://www.c-sharpcorner.com/Blogs/9421/add-remove-or-modify- ...

  5. hdu 4700 那个啥树

    思路:我也不知道叫什么树,但是构造过程能理解. 我们可以将先将边按降序排序,那么就用kruskaer构造生成树.构造好的生成树也就是满足条件的图,因为点i,j的最大流量就是生成树上点i到点j的路径上的 ...

  6. spring项目中如何添加定时器以及在定时器中自动生成sprng注入对象

    最近做了一个java的项目,部门领导给了一套代码让我尽快掌握,说心里话本人真心不喜欢java的这种项目方式,各种配置各种xml文件简直头都大了,下面就将我遇到的其中一个我认为是坑的地方整理出来,希望能 ...

  7. Ubuntu 15.04 无损扩展分区(目录)容量的方法 (无需格式化, 文件不丢失)

    源 起 用了一段时间Ubuntu,碰到了UBuntu磁盘空间不足的问题, 最初我只给Ubuntu分配了30个G的空间, 昨天试用了一下VirtualBox安装了一个xp虚拟系统,用以解决Ubuntu下 ...

  8. android菜鸟学习笔记2----关于adb

    adb : android debug bridge android调试桥 路径:adt-bundle目录/sdk/platform-tools/adb.exe 常见的adb命令: adb devic ...

  9. Android 开源项目分类汇总

    Android 开源项目分类汇总 Android 开源项目第一篇——个性化控件(View)篇  包括ListView.ActionBar.Menu.ViewPager.Gallery.GridView ...

  10. asp.net判断访问者是否来自移动端

    主要就是通过客户端传递的User-agent来判断访问网站的客户端是PC还是手机. .NET中就是Request.ServerVariables["HTTP_USER_AGENT" ...