Computer >> 컴퓨터 >  >> 프로그램 작성 >> MongoDB

고유 사용자 ID의 시퀀스를 저장하기 위해 MongoDB에서 자동 증가?

<시간/>

고유한 사용자 ID의 시퀀스를 저장하기 위해 MongoDB에서 자동 증가하려면 모든 문서의 마지막 시퀀스 값에 대한 정보를 포함하는 컬렉션을 생성합니다.

먼저 컬렉션을 생성해 보겠습니다. 다음과 같은 컬렉션을 생성하는 쿼리 -

> db.createSequenceDemo.insertOne({_id:"SID",S_Value:0});{ "승인됨":true, "insertedId":"SID" }

이제 MongoDB에서 시퀀스를 저장하기 위해 자동 증분을 생성하는 함수를 만들 것입니다. 쿼리는 다음과 같습니다 -

> function nextSequence(s) { ... var sd =db.createSequenceDemo.findAndModify({ ... 쿼리:{_id:s }, ... 업데이트:{$inc:{S_Value:1}}, ... 새로운:참 ... }); ... sd.S_Value 반환;... }

몇 가지 문서로 컬렉션을 만들고 고유한 사용자 ID의 시퀀스를 생성하기 위해 위의 함수를 호출합시다.

문서로 컬렉션을 생성하는 쿼리는 다음과 같습니다 -

> db.checkSequenceDemo.insertOne({"StudentId":nextSequence("SID"),"StudentName":"Larry","StudentMathMarks":78});{ "승인됨":true, "insertedId":ObjectId ("5c7f61008d10a061296a3c40")}> db.checkSequenceDemo.insertOne({"StudentId":nextSequence("SID"),"StudentName":"마이크","StudentMathMarks":89});{ "확인됨" " :ObjectId("5c7f61118d10a061296a3c41")}> db.checkSequenceDemo.insertOne({"StudentId":nextSequence("SID"),"StudentName":"Sam","StudentMathMarks":{"acknowled"); , "insertedId" :ObjectId("5c7f611d8d10a061296a3c42")}

find() 메서드를 사용하여 컬렉션의 모든 문서를 표시합니다. 쿼리는 다음과 같습니다 -

> db.checkSequenceDemo.find().pretty();

다음은 출력입니다 -

{ "_id":ObjectId("5c7f61008d10a061296a3c40"), "StudentId":1, "StudentName":"래리", "StudentMathMarks"4c:78}{ "_id":ObjectId("581f61011 :2, "StudentName" :"Mike", "StudentMathMarks" :89}{ "_id" :ObjectId("5c7f611d8d10a061296a3c42"), "StudentId" :3, "StudentName" :"Sam", "StudentMath6Mark /사전> 

자동으로 1씩 증가하는 "StudentId" 필드를 봅니다.