JIYIK CN >

Current Location:Home > Learning > DATABASE > MongoDB >

Generate ObjectId in MongoDB using Java

Author:JIYIK Last Updated:2025/04/29 Views:

In any database, we need to organize the data in a way that we can easily find that data when necessary. To do this, it is very important to create a unique identity.

In MongoDB, there is a built-in unique identification system using a field called ObjectId.

This article will discuss ObjectId and how we can generate it using Java program. To make the topic easier, we will see an example with explanation to make the topic easier.


ObjectId in MongoDB

ObjectId is the value that uniquely identifies a document in MongoDB through the field _id. When a user inserts a new document, the system automatically generates this field.

But sometimes, we have to create our own ObjectId according to our own preferences to provide a unique identifier for each document. If you are creating a Java program that can operate a MongoDB database, then you can check out the next section on generating ObjectId using Java.


Generate ObjectId using Java

In the following example, we will demonstrate how to create a Java program that can insert a document using a manually created ObjectId. To do this, you can check the following example.

import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.bson.types.ObjectId;
import com.mongodb.MongoClient;


public class MongoDBJava {

    public static void main(String[] args) {
        MongoClient mongoClient = new MongoClient( "localhost" , 27017 );

        // Selecting the database
        MongoDatabase mydb = mongoClient.getDatabase("Mydb");

        // Generating an ObjectId before creating the document
        ObjectId myid = new ObjectId();

        System.out.println("Generated ID: "+ myid.get());

        // Creating a new document object
        Document mydoc = new Document();

        // Appending data to the document
        mydoc.append("_id", myid);
        mydoc.append("Name", "Fred");
        mydoc.append("Email", "Fred@gmail.com");
        mydoc.append("Year", 2022);

        //Inserting the created document into the collection
        mydb.getCollection("mydata").insertOne(mydoc);
        System.out.println("Inserted document successfully");
    }
}

The purpose of each line is commented out. In the example, we first create a connection to the MongoDB database.

After that, we use the method getDatabase()select database and then generate a new ObjectId called myid.

We then created a Document object and append()appended the data to it using the method. Finally, we simply insertOne()inserted the document into our collection using the method.

After executing the above example, you will get the following output.

Generated ID: 6383c46f57dfc2483d89093c
Inserted document successfully

You will see the following document added to your MongoDB collection.

{ _id: ObjectId("6383c46f57dfc2483d89093c"),
  Name: 'Fred',
  Email: 'Fred@gmail.com',
  Year: 2022 }

Some important notes:

  1. The program shared in this article is written in Java. So, make sure it is installed in your system.
  2. First install and include the MongoDB jar file in your Java program. To download MongoDB jar, use this link.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

List all collections in MongoDB Shell

Publish Date:2025/04/29 Views:156 Category:MongoDB

When using MongoDB , there are several ways to list the collections in the database. This article will discuss four different ways to get a list of collections in a MongoDB database. These methods are as follows: show collections List all c

Querying for non-null values in MongoDB

Publish Date:2025/04/29 Views:139 Category:MongoDB

This MongoDB article will explain how to query for non-null values ​​in MongoDB. To query for non-null values, you can use $ne the operator and $eq the operator and then specify the desired value to query. This article shows the readers

Shutting down with code:100 error in MongoDB

Publish Date:2025/04/29 Views:53 Category:MongoDB

This MongoDB tutorial will teach you to fix the error on different operating systems shutting down with code:100 . It will also talk about the root cause of why this issue occurs. shutting down with code:100 Errors in MongoDB As we all know

SELECT COUNT GROUP BY in MongoDB

Publish Date:2025/04/29 Views:74 Category:MongoDB

In this article, we will discuss the functions in MongoDB. Also, we will point out the aggregation functions in detail. We will explain in detail the different ways to count and sort multiple and single fields of Group in MongoDB. Operation

Differences between MongoDB and Mongoose

Publish Date:2025/04/29 Views:80 Category:MongoDB

This MongoDB article will discuss the differences between MongoDB and Mongoose. Unfortunately, most beginners tend to confuse these two concepts when they start developing applications and use MongoDB as their backend. MongoDB has its own s

Install MongoDB using Homebrew

Publish Date:2025/04/29 Views:161 Category:MongoDB

MongoDB is a well-known unstructured database management system that can handle large amounts of data. It is a document-oriented database system and belongs to the NoSQL family (non-SQL). Data and records are stored as documents that look a

Create a MongoDB dump of the database

Publish Date:2025/04/29 Views:62 Category:MongoDB

In this MongoDB article, you’ll get a walkthrough of Mongodump and Mongorestore , how to use them, and some simple examples of backing up and restoring your collections using both tools. mongodump Commands in MongoDB Mongodump is a tool t

Get the size of the database in MongoDB

Publish Date:2025/04/29 Views:88 Category:MongoDB

When working in MongoDB, do you know the size of your database? Today, we will learn how to get the size of a database in MongoDB using show dbs the command and the method. db.stats() Get the size of the database in MongoDB We can show dbs;

Grouping values by multiple fields with MongoDB

Publish Date:2025/04/29 Views:99 Category:MongoDB

MongoDB Group by Multiple Fields is used to group values ​​by multiple fields using various methods. One of the most efficient ways to group various fields present in MongoDB documents is by using $group the operator, which helps in per

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial