MongoDB Long/Int(长整型)的自增长主键 解决方案
今朝有幸尝芒果,发现自增长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(长整型)的自增长主键 解决方案的更多相关文章
- python基础知识2——基本的数据类型——整型,长整型,浮点型,字符串
磨人的小妖精们啊!终于可以归置下自己的大脑啦,在这里我要把--整型,长整型,浮点型,字符串,列表,元组,字典,集合,这几个知识点特别多的东西,统一的捯饬捯饬,不然一直脑袋里面乱乱的. 对于Python ...
- Python基础:数值(布尔型、整型、长整型、浮点型、复数)
一.概述 Python中的 数值类型(Numeric Types)共有5种:布尔型(bool).整型(int).长整型(long).浮点型(float)和复数(complex). 数值类型支持的主要操 ...
- Python基础:1.数据类型(空、布尔类型、整型、长整型、浮点型、字符串)
提示:python版本2.7,windows系统 Python提供的基本数据类型:空.布尔类型.整型.长整型.浮点型.字符串.列表.元组.字典.日期 1.空(None) None,是一个特殊的值,不能 ...
- javascript没有长整型
记录一下前几天踩坑的经历. 背景:一个项目某一版之后很多用easyui的表格控件treegrid渲染的表格都显示不出来了 奇怪的地方主要有以下几点: 项目在测试环境才会这样,在本机能够正常运行,多次重 ...
- PHP长整型在32位系统中强制转化溢出
CleverCode近期遇到一个PHP项目整形转化问题,mysql有一个字段id是bigint的,里面有长整型,如id = 5147486396.可是php代码因为历史原因却部署在多台机器中,当中A机 ...
- 零基础如何学好Python 之int 数字整型类型 定义int()范围大小转换
本文主题是讲python数字类型python int整型使用方法及技巧.它是不可变数据类型中的一种,它的一些性质和字符串是一样的,注意是整型不是整形哦. Python int有多种数字类型:整型int ...
- Mac地址转换成long长整型 2
数据之间的转换可以使用 System.Convert Mac地址转换成long长整型 /// <summary> /// 解析长整形的数据使其转换为macID /// </sum ...
- Mac地址转换成long长整型
Mac地址转换成long长整型 using System;using System.Collections.Generic;using System.IO;using System.Text;usin ...
- 整型,长整型,无符号整型等 大端和小端(Big endian and Little endian)
一.大端和小端的问题 对于整型.长整型.无符号整型等数据类型,Big endian 认为第一个字节是最高位字节(按照从低地址到高地址的顺序存放数据的高位字节到低位字节):而 Little endian ...
随机推荐
- iOS- SQLite3的基本使用
iOS- 简单说说iOS移动客户端SQLite3的基本使用 1.为什么要使用SQLite3? •大量数据需要存储 •管理数据,存储数据 SQLite是一种关系型数据库(也是目前移动客户端的主 ...
- PetaPoco使用要点
PetaPoco是一款适用于.Net 和Mono的微小.快速.单文件的微型ORM! 可以从这里获得PetaPoco: NuGet - http://nuget.org/List/Packages/Pe ...
- [C.Sharp] TimeSpan的用法,获取测试程序运行时间
TimeSpan的用法 TimeSpan是用来表示一个时间段的实例,两个时间的差可以构成一个TimeSpan实例,现在就来简单介绍一下几点重要的用法: a 先来介绍几个方法 TimeSpan.Minu ...
- [Java] 遍历HashMap和HashMap转换成List的两种方式
遍历HashMap和HashMap转换成List /** * convert the map to the list(1) */ public static void main(String[] ...
- JavaScript 编写线程代码引用Concurrent.Thread.js
马上来下载和使用源码吧!假定你已经将下载的源码保存到一个名为Concurrent.Thread.js的文件夹里,在进行任何操作之前,先运行如下程序,这是一个很简单的功能实现: <script t ...
- linux初学 :linux 常用命令(一)
首先,是关机/重启命令,仅在虚拟机时使用,实际工作中用不到 reboot 一般不跟参数使用,输入指令即可重启 shutdown 一般需要跟参数,例: shutdown -r 延时多少分钟重启,一般使用 ...
- php实现二路归并排序
$arr = [9, 43, 12, 0, 87, 1]; function merge_sort(&$arr){ _merge_sort($arr, $arr, 0, count($arr) ...
- Python中的内置函数
2.1 Built-in Functions The Python interpreter has a number of functions built into it that are alway ...
- 有一种风格,叫做 Low Poly 3D
原作:Simon阿文 杂交编辑者:RhinoC 个人更推崇使用第二款神器 ImageTriangulator :http://www.conceptfarm.ca/2013/port ...
- html5 Canvas API
详细内容请点击 1.HTML Canvas API有两方面优势可以弥补:首先,不需要将所绘制图像中的每个图元当做对象存储,因此执行性能非常好:其次,在其他编程语言现有的优秀二维绘图API的基础上实现C ...