ObjectID() Function: MongoDB uses ObjectID to create unique identifiers for all the documents in the database. It is different than the traditional autoincrementing integer ID, but it comes with its own set of advantages.
An ObjectID is a GUID (Globally Unique Identifier). GUIDs are generated randomly via an algorithm to ensure uniqueness. These IDs can be generated on the server, but as seen in the snippet above, they can be generated on the client as well. That means a client can generate the ID for a document it’s about to insert into the database.
Installation of mongodb module:
- You can visit the link to Install mongodb module. You can install this package by using this command.
npm install mongodb
- After installing mongodb module, you can check your mongodb version in command prompt using the command.
npm version mongodb
- After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.
MongoDB provides ObjectID which can be used to generate new ObjectIDs. The example below generates a new ID and prints it to the console.
Steps to run the program:
- The project structure will look like this:
- Make sure you have installed mongodb module using following command:
npm install mongodb
- Run index.js file using below command:
So this is how you can use the MongoDB ObjectID() function to create unique identifiers for all the documents in the database.
- Nodejs - Connect MongoDB with Node app using MongooseJS
- Signup Form Using Nodejs and MongoDB
- Introduction about Node.js and MongoDB
- MongoDB | Create Database using MongoShell
- MongoDB | Delete Database using MongoShell
- Defining, Creating and Dropping a MongoDB collection
- How to Install and Configure MongoDB in Ubuntu?
- MongoDB Tutorial in Java
- Upload and Retrieve Image on MongoDB using Mongoose
- MongoDB - Comparison Query Operators
- MongoDB - Logical Query Operators
- MongoDB - Field Update Operators
- MongoDB - Multiply Operator ($mul)
- MongoDB - Rename Operator ($rename)
- MongoDB - Current Date Operator ($currentDate)
- MongoDB - SetOnInsert Operator ($setOnInsert)
- MongoDB - Positional Operator ($)
- MongoDB - $pull Operator
- MongoDB - $each Modifier
- MongoDB - $push Operator
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.