有道云笔记地址:http://note.youdao.com/yws/public/redirect/share?id=15b13e7c458cf2e1e28463b23835aa32&type=false
mongodb中 会自动生成字段 ”_id“ ,类型为 ObjectId,mongodb默认在ObjectId上建立索引,是按照插入时间排序。
ObjectId 构成
ObjectId 是一个12个字节的 bson 类型字符串,按照字节顺序,依次代表以下不同含义:
TimeStamp 》4字节:UNIX时间戳(16进制的时间戳,精确到秒)
Machine 》3字节:表示运行MongoDB 的机器唯一标识(一般是机器名的hash值,确保分布式环境中不同机器生成值不冲突)
pid 》2字节:表示生成ObjectId的进程号(pid)
increment 》3字节:由随机数开始的计数器,用来确保同一秒内生成的 objectid 不进行冲突, 允许 256的3次方====16777216 条记录的唯一性
特别说明,认情况下ObjectId是由客户端生成,并不是不设置就由服务端生成的。(mongoDB的驱动包中是会自动添加ObjectId)
以下是部分源码
- protected WriteResult insert(List<DBObject> list, boolean shouldApply , com.mongodb.WriteConcern concern, DBEncoder encoder ){
-
- if (encoder == null)
- encoder = DefaultDBEncoder.FACTORY.create();
-
- if ( willTrace() ) {
- for (DBObject o : list) {
- trace( "save: " + _fullNameSpace + " " + JSON.serialize( o ) );
- }
- }
-
- if ( shouldApply ){
- for (DBObject o : list) {
- apply(o);
- _checkObject(o, false, false);
- Object id = o.get("_id");
- if (id instanceof ObjectId) {
- ((ObjectId) id).notNew();
- }
- }
- }
-
- WriteResult last = null;
-
- int cur = 0;
- int maxsize = _mongo.getMaxBsonObjectSize();
- while ( cur < list.size() ) {
-
- OutMessage om = OutMessage.insert( this , encoder, concern );
-
- for ( ; cur < list.size(); cur++ ){
- DBObject o = list.get(cur);
- om.putObject( o );
-
- // limit for batch insert is 4 x maxbson on server, use 2 x to be safe
- if ( om.size() > 2 * maxsize ){
- cur++;
- break;
- }
- }
-
- last = _connector.say( _db , om , concern );
- }
-
- return last;
- }
- /**
- * calls {@link DBCollection#apply(com.mongodb.DBObject, boolean)} with ensureID=true
- * @param o <code>DBObject</code> to which to add fields
- * @return the modified parameter object
- */
- public Object apply( DBObject o ){
- return apply( o , true );
- }
-
- /**
- * calls {@link DBCollection#doapply(com.mongodb.DBObject)}, optionally adding an automatic _id field
- * @param jo object to add fields to
- * @param ensureID whether to add an <code>_id</code> field
- * @return the modified object <code>o</code>
- */
- public Object apply( DBObject jo , boolean ensureID ){
-
- Object id = jo.get( "_id" );
- if ( ensureID && id == null ){
- id = ObjectId.get();
- jo.put( "_id" , id );
- }
-
- doapply( jo );
-
- return id;
- }
- public WriteResult save( DBObject jo, WriteConcern concern ){
- if ( checkReadOnly( true ) )
- return null;
-
- _checkObject( jo , false , false );
-
- Object id = jo.get( "_id" );
-
- if ( id == null || ( id instanceof ObjectId && ((ObjectId)id).isNew() ) ){
- if ( id != null && id instanceof ObjectId )
- ((ObjectId)id).notNew();
- if ( concern == null )
- return insert( jo );
- else
- return insert( jo, concern );
- }
-
- DBObject q = new BasicDBObject();
- q.put( "_id" , id );
- if ( concern == null )
- return update( q , jo , true , false );
- else
- return update( q , jo , true , false , concern );
-
- }
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于