shankyyyyyyy
shankyyyyyyy

Reputation: 97

Pymongo : keep creating new ids

In a pymongo project I'm working on, in a particular collection, I have to keep uploading name and age of people who will be entering them. I have to identify them with unique ids.

What I as planning to do is start the first id from 1. When inserting data, I first read the whole collection, find the number of records and then save my record with the next id. (eg. I read, and I find that there are 10 records, then the id of my new record will be 11).

But is there any better way to do it?

Upvotes: 0

Views: 112

Answers (1)

Shafqat Jamil Khan
Shafqat Jamil Khan

Reputation: 1037

MongoDB already assigns unique id to each document which can be sorted in ascending order. If you don't wanna use that then you can create a separate collection which should just contain 1 document with totalRecordsCount. And increment it every time you add new record and get latest number before adding new record. This is not a best way but you will be able to avoid reading whole collection.

Upvotes: 1

Related Questions