Skip to content
Related Articles

Related Articles

MongoDB | ObjectID() Function
  • Last Updated : 05 Jun, 2020

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:

  1. You can visit the link to Install mongodb module. You can install this package by using this command.
    npm install mongodb
  2. After installing mongodb module, you can check your mongodb version in command prompt using the command.
    npm version mongodb
  3. 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.
    node index.js

MongoDB provides ObjectID which can be used to generate new ObjectIDs. The example below generates a new ID and prints it to the console.

Filename: index.js






const { MongoClient, ObjectID } = require('mongodb');
const id = new ObjectID();
  
// Print new id to the console
console.log(id); 

Steps to run the program:

  1. The project structure will look like this:
  2. Make sure you have installed mongodb module using following command:
    npm install mongodb
  3. Run index.js file using below command:
    node index.js

So this is how you can use the MongoDB ObjectID() function to create unique identifiers for all the documents in the database.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :