Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Databases Mongo Basics Getting Started With MongoDB Review: Documents

Why is _id field mandatory ? Is it mandatory for every record? Also can it be system generated ?

Why is _id field mandatory ? Is it mandatory for every record? Also can it be system generated ?

2 Answers

Ari Misha
Ari Misha
19,323 Points

Hiya Aditi! "_id " is always mandatory. Its a primary key for every document in Mongo. They're like identification and unique and makes your life easier especially when you query the database and hey its considered best practice as well. But there is one gotcha in Mongo. Attempting to use an "id"(not to mistaken with "_id") key may result in a illegal ObjectId format error so yeah look out for those. Also , "_id" is generated with timestamps , so yeah its easier to keep track of Mongo documents. In my opinion its pretty awesome that " _id" is automatically indexed in every collection.

Ken Alger
STAFF
Ken Alger
Treehouse Teacher

Aditi-

As Ari Misha mentioned, each document in a MongoDB collection has an _id. By default _id is assigned an ObjectId value which includes a lot of different information. Part of that information, the first four of the twelve bits, is a timestamp. Based on the specifications for MongoDB, ObjectId's are guaranteed to be unique in a single collection, but not necessarily across collections.

However, one can also generate and assign values to the _id field. There are definitely some use cases for that. However, most of the time I find it best to let MongoDB generate the _id field and then if it is necessary for the application to have another per document unique field, create that separately. Have a look here for an example of some reasons that not using an ObjectId might be a good idea.

As with most database schema designs, how you plan on using your data will have a large impact on the "best" method for storing the data.

Post back if you have further questions or want to discuss MongoDB in further detail.

Happy coding! Ken