在 MongoDB 中自动增加存储唯一用户 ID 序列?
若要通过自动增加的方式在 MongoDB 中存储唯一用户 ID 序列,请创建包含所有文档的最后序列值的集合。
我们先创建一个集合。创建集合的查询如下 −
> db.createSequenceDemo.insertOne({_id:"SID",S_Value:0});
{ "acknowledged" : true, "insertedId" : "SID" }接着,我们将创建一个函数生成自动增加的方式在 MongoDB 中存储序列。查询如下 −
> function nextSequence(s) {
... var sd = db.createSequenceDemo.findAndModify({
... query:{_id: s },
... update: {$inc:{S_Value:1}},
... new:true
... });
... return sd.S_Value;
... }让我们使用一些文档创建一个集合,并调用上述函数来生成唯一用户 ID 序列。
使用文档创建集合的查询如下 −
> db.checkSequenceDemo.insertOne({"StudentId":nextSequence("SID"),"StudentName":"Larry","StudentMathMarks":78});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c7f61008d10a061296a3c40")
}
> db.checkSequenceDemo.insertOne({"StudentId":nextSequence("SID"),"StudentName":"Mike","StudentMathMarks":89});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c7f61118d10a061296a3c41")
}
> db.checkSequenceDemo.insertOne({"StudentId":nextSequence("SID"),"StudentName":"Sam","StudentMathMarks":67});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c7f611d8d10a061296a3c42")
}使用 find() 方法显示集合中的所有文档。查询如下 −
> db.checkSequenceDemo.find().pretty();
输出如下 −
{
"_id" : ObjectId("5c7f61008d10a061296a3c40"),
"StudentId" : 1,
"StudentName" : "Larry",
"StudentMathMarks" : 78
}
{
"_id" : ObjectId("5c7f61118d10a061296a3c41"),
"StudentId" : 2,
"StudentName" : "Mike",
"StudentMathMarks" : 89
}
{
"_id" : ObjectId("5c7f611d8d10a061296a3c42"),
"StudentId" : 3,
"StudentName" : "Sam",
"StudentMathMarks" : 67
}查看按 1 自动增加的字段“StudentId”
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP