SoFunction
Updated on 2025-05-22

Several common ways to map MongoDB_id fields

Several common ways to map MongoDB_id fields

Updated: May 22, 2025 09:42:19 Author: Bingtangxin Study Room
In Spring Data MongoDB, mapping the Java POJO field to the _id field of the MongoDB document is very direct, mainly done through @Id annotation (). This article introduces several common ways and key points for mapping the MongoDB _id field. Friends who need it can refer to it.

In Spring Data MongoDB, map fields of Java POJO to MongoDB documents_idThe fields are very direct, mainly through@IdAnnotation () to complete.

The following is the mapping MongoDB_idSeveral common ways and key points of fields:

1. Use the String type as ID (most common):

  • when@IdThe field type of annotated isStringSpring Data MongoDB will treat it as MongoDBObjectIdThe string representation form.
  • ifWhen saving a new documentStringThe field isnull, the MongoDB Java driver will automatically generate a new oneObjectId, and then Spring Data MongoDB converts it to a string and assigns a value to the field.
  • This is the most recommended and convenient way, because IDs in string form are easier to use in APIs, URLs, and logs.
import ;
import ;

@Document(collection = "my_entities")
public class MyEntity {

    @Id
    private String id; // Map to MongoDB's _id field
    private String name;

    // Constructors, getters, setters
    public String getId() {
        return id;
    }

    public void setId(String id) {
         = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
         = name;
    }
}

When you save a new oneMyEntityExamples andidThe field isnullhour:

MyEntity entity = new MyEntity();
("Test Entity");
(entity); // () There will now be an automatically generated ObjectId string(()); // For example: "60c72b941f4b1a3e4c8e4f3a"

2. Use the type as ID:

  • You can directly use the MongoDB BSON library provided byObjectIdtype.
  • Similarly, ifWhen saving a new documentObjectIdThe field isnull, the driver will automatically generate a new oneObjectId
import ;
import ;
import ;

@Document(collection = "products")
public class Product {

    @Id
    private ObjectId id; // Use the ObjectId type directly
    private String productName;

    // Constructors, getters, setters
    public ObjectId getId() {
        return id;
    }

    public void setId(ObjectId id) {
         = id;
    }

    public String getProductName() {
        return productName;
    }

    public void setProductName(String productName) {
         = productName;
    }
}

3. Use other Java types as IDs (for example, Long, BigInteger):

  • You can also use other primitive types or object types (such asLongBigInteger) As_id
  • important: If these types are used,MongoDB will not automatically generate IDs for you. You must provide a unique ID value yourself before saving the document. If the field isnull(For object types) or default values ​​(for primitive types and you did not set them) may cause errors or unexpected behavior, depending on the driver and server version.
  • This method is suitable for situations where you have an external system generated ID, or the ID has a specific business meaning.
import ;
import ;
import ;

@Document(collection = "items")
public class Item {

    @Id
    private Long itemId; // Use Long type, you need to ensure uniqueness and assign values ​​by yourself
    // or    // @Id
    // private BigInteger itemId; // Using BigInteger, you need to ensure uniqueness and assign values ​​by yourself
    private String description;

    // Constructors, getters, setters
    public Long getItemId() {
        return itemId;
    }

    public void setItemId(Long itemId) {
         = itemId;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
         = description;
    }
}

When using a custom ID:

Item item = new Item();
(12345L); // ID must be set manually("Custom ID Item");
(item);

4. The Java field name does not necessarily mean "id":

  • quilt@IdThe name of the annotated Java field may be different.id. Spring Data MongoDB will still map it to the MongoDB document_idField.
import ;
import ;

@Document(collection = "books")
public class Book {

    @Id
    private String bookIsbn; // The Java field is named "bookIsbn", but it maps to MongoDB's _id
    private String title;

    // Getters and setters
    public String getBookIsbn() {
        return bookIsbn;
    }

    public void setBookIsbn(String bookIsbn) {
         = bookIsbn;
    }
    // ...
}

Summary of key points:

  • @IdNote: It is to mark the Java field as MongoDB_idThe core of  .
  • Automatically generate:
    • Only if@IdThe field type isStringor, and when inserting a new document, the field value isnullOnly when the ID is automatically generated by MongoDB driver.
    • Other types (such asLongIntegerBigInteger) You need to manually assign values ​​in the application and ensure their uniqueness.
  • Immutability: In MongoDB_idOnce a field is set, it cannot be modified. Try updating_idCan cause the operation to fail or create a new document (depending on the operation type).
  • Uniqueness_idMust be unique in its collection. MongoDB will automatically_idFields create unique indexes.
  • @Field("_id"): Usually not required.@IdThe annotation itself implies that the Java field maps to the BSON document_idKey. Use explicitly@Field("_id")It's redundant.

Which ID type to choose depends on your specific needs:

  • String(ObjectId string): Universal, convenient, recommended for most scenarios.
  • ObjectId: If you need to operate directly in Java codeObjectIdObject (for example, get the timestamp part).
  • Long / BigInteger/ Other custom types: When the ID has a specific business meaning or is generated by an external system.

In most Spring Boot applications, useStringType and let MongoDB automatically generateObjectIdIt is the easiest and most common practice.

The above is the detailed content of several common ways to map MongoDB _id fields. For more information about mapping MongoDB _id fields, please follow my other related articles!

  • Mapping
  • MongoDB
  • id
  • Fields

Related Articles

  • SpringBoot integrates redis and mongodb in detail

    This article mainly introduces SpringBoot integration of redis and mongodb. In this section, we will turn our focus to NoSQL. The article will explain it to you in detail in combination with the sample code. Friends who need it can refer to it.
    2022-10-10
  • YUM source installation mongodb graphic tutorial

    This article introduces you to a detailed graphic tutorial on installing MongoDB using yum source. Friends, follow the tutorial step by step. I hope you like it.
    2018-09-09
  • MongoDB Quick Start Notes (7) MongoDB User Management Operations

    This article mainly introduces the MongoDB Quick Start Notes (7) related information about MongoDB's user management operations. Friends who need it can refer to it.
    2016-06-06
  • Guide to Install MongoDB using commands (Windows, Linux)

    This article mainly introduces the guide to installing MongoDB using commands. This article introduces the method of installing mongodb using commands under Windows and Linux. Friends who need it can refer to it
    2015-04-04
  • The difference comparison table between MongoDB Community Edition and Enterprise Edition

    This article mainly introduces the difference comparison table between MongoDB community version and enterprise version. This article provides a comparison table for Chinese and English versions. Friends who need it can refer to it.
    2014-10-10
  • In-depth explanation of MongoDB's slow log query (profile)

    In MySQL, slow query logs are often used as the basis for our optimization of databases. So is there a similar function in MongoDB? The answer is yes, that is MongoDB Database Profiler. The following article mainly introduces relevant information about MongoDB slow log query (profile). Friends who need it can refer to it.
    2017-06-06
  • Detailed installation tutorial for MongoDB uninstallation and installation

    MongoDB is a database based on distributed file storage. The following article mainly introduces relevant information about MongoDB uninstallation and installation. The article introduces the example code in detail. Friends who need it can refer to it.
    2023-04-04
  • Detailed explanation of Mongoose's use in egg

    This article mainly introduces the use of Mongoose in egg. This article introduces you very detailedly and has certain reference value for your study or work. Friends who need it can refer to it.
    2020-06-06
  • Analysis of the process of creating an account and library with ubuntu installation and adding coordinate indexes

    This article mainly introduces the process analysis of the process of installing mongodb on ubuntu to create an account and library and adding coordinate indexes. This article introduces you very detailedly and has certain reference value for your study or work. Friends who need it can refer to it.
    2020-10-10
  • Install MongoDB in Ubuntu and perform some simple operation notes

    This article mainly introduces the installation of MongoDB and performing some simple operation notes in Ubuntu. This article also provides examples of operation commands such as viewing existing databases, deleting databases, and creating databases. Friends who need it can refer to it.
    2014-09-09

Latest Comments