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 ...
随机推荐
- .net对各表的操作详细到字段的更改记录的日志
存入数据库中,目前的字段包括操作人,操作时间,sql语句,被修改的字段,字段原值,操作人的身份. /// <summary> /// 添加操作日志 /// </summary> ...
- 【Mood-7】tell 2 my gf-miss u not sudden but always
#sorry not coming 2 see u the national day holiday! I'm BULL in the land,fighting 4 u and babies! # ...
- 《算法导论》习题解答 Chapter 22.1-2(邻接矩阵与链表)
链表如图: 矩阵: 1 2 3 4 5 6 7 1 0 1 1 0 0 0 0 2 1 0 0 1 1 0 0 3 1 0 0 0 0 1 1 4 0 1 0 0 0 0 0 5 0 1 0 0 0 ...
- 重构19-Extract Factory Class(提取工厂类)
在代码中,通常需要一些复杂的对象创建工作,以使这些对象达到一种可以使用的状态.通常情况下,这种创建不过是新建对象实例,并以我们需要的方式进行工作.但是,有时候这种创建对象的需求会极具增长,并且混淆了创 ...
- Ubuntu下安装QT
环境 Ubuntu 9.10 qt4.7.3 gcc 4.4 Ubuntu中缺少 make 首先安装 sudo apt-get install make 如果不知道缺少啥,就按下面的装 1.sudo ...
- eclipse启动问题
今天在公司正上班,突然跳出来一个windows update补丁更新,然后就确认呗,结果更新完成之后, eclipse打不开了,启动报错: could not find the main class, ...
- c# 结课小结
C#总结知识点 模块一:知识点梳理 输入输出表达式---数据类型---变量与常量 ----运算符---语句-----数组与集合---函数--结构体: 模块二:输入与输出 输入: console.re ...
- Python之时间统计
1. import time start_time = time.time() print('time %ds'%(time.time() - start_time))
- Sqlite3笔记
.tables 查看表.databases 创建数据库alter table 表名 RENAME TO 新表名ALTER TABLE 表名 add column 列名 datatype [DEFAUL ...
- css优先机制
样式的优先级 (外部样式)External style sheet <(内部样式)Internal style sheet <(内联样式)Inline style (内部样式就是css写在 ...