Several common ways to map MongoDB_id fields
In Spring Data MongoDB, map fields of Java POJO to MongoDB documents_id
The fields are very direct, mainly through@Id
Annotation () to complete.
The following is the mapping MongoDB_id
Several common ways and key points of fields:
1. Use the String type as ID (most common):
- when
@Id
The field type of annotated isString
Spring Data MongoDB will treat it as MongoDBObjectId
The string representation form. - ifWhen saving a new document
String
The 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 oneMyEntity
Examples andid
The field isnull
hour:
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 by
ObjectId
type. - Similarly, ifWhen saving a new document
ObjectId
The 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 as
Long
,BigInteger
) 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 is
null
(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
@Id
The name of the annotated Java field may be different.id
. Spring Data MongoDB will still map it to the MongoDB document_id
Field.
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:
-
@Id
Note: It is to mark the Java field as MongoDB_id
The core of . -
Automatically generate:
- Only if
@Id
The field type isString
or, and when inserting a new document, the field value is
null
Only when the ID is automatically generated by MongoDB driver. - Other types (such as
Long
,Integer
,BigInteger
) You need to manually assign values in the application and ensure their uniqueness.
- Only if
-
Immutability: In MongoDB
_id
Once a field is set, it cannot be modified. Try updating_id
Can cause the operation to fail or create a new document (depending on the operation type). -
Uniqueness:
_id
Must be unique in its collection. MongoDB will automatically_id
Fields create unique indexes. -
@Field("_id")
: Usually not required.@Id
The annotation itself implies that the Java field maps to the BSON document_id
Key. 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 codeObjectId
Object (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, useString
Type and let MongoDB automatically generateObjectId
It 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!
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-10YUM 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-09MongoDB 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-06Guide 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 it2015-04-04The 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-10In-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-06Detailed 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-04Detailed 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-06Analysis 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-10Install 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