MongoDB _id Key的一些信息

关于 mongodb _id key:

  1. _id key可以用户分配,也可以由mongodb自动分配,一般采用自动分配。
  2. 如果未使用_id作为分片key,则应用程序或客户端层要负责保证_id为唯一的,对于collection存在重复_id会有问题。If you do not use _id as the shard key, then your application/client layer must be responsible for keeping the _id field unique. It is problematic for collections to have duplicate _id values.
  3. 更新一个document 不会造成_ID被修改

对于更新一个document 不会造成_ID被修改的证明:

> db.version();
3.0.2

> db.dbdao_student.insert({student_name:"maclean",age:20,sex:"male",score:100});
WriteResult({ "nInserted" : 1 })

> db.dbdao_student.update({student_name:"maclean"},{"student_name" : "maclean", "age" : 20, "sex" : "male", "score" : 100});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
>
> db.dbdao_student.find();
{ "_id" : ObjectId("5545bcff5714fbdfcb483510"), "student_name" : "maclean", "age" : 20, "sex" : "male", "score" : 100 }
>
> db.dbdao_student.update({student_name:"maclean"},{"student_name" : "maclean", "age" : 21, "sex" : "male", "score" : 100});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.dbdao_student.find();
{ "_id" : ObjectId("5545bcff5714fbdfcb483510"), "student_name" : "maclean", "age" : 21, "sex" : "male", "score" : 100 }
>
> db.dbdao_student.update({student_name:"maclean"},{"student_name" : "maclean", "age" : 25, "sex" : "male", "score" : 100});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
>
> db.dbdao_student.find();
{ "_id" : ObjectId("5545bcff5714fbdfcb483510"), "student_name" : "maclean", "age" : 25, "sex" : "male", "score" : 100 }
>
> db.dbdao_student.update({student_name:"maclean"},{"student_name" : "maclean", "age" : 25});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.dbdao_student.find();
{ "_id" : ObjectId("5545bcff5714fbdfcb483510"), "student_name" : "maclean", "age" : 25 }

> db.dbdao_student.find(ObjectId("5545bcff5714fbdfcb483510"));
{ "_id" : ObjectId("5545bcff5714fbdfcb483510"), "student_name" : "maclean", "age" : 25 }

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *