MongoDB 中如何自动增量存储唯一用户 ID 序列?
mongodbdatabasebig data analytics更新于 2026/1/17 7:22:17
要在 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
}
查看字段"StudentId",它自动增加 1

