MongoDB Auto-Increment fields in document
Today in this article will see how to perform an update to the mongo document and MongoDB Auto-Increment fields in the update or insert operation. This auto-increment could be needed to keep the uniqueness of similar updates or there could be multiple use cases where you might need this feature.
Today in this article, we will cover below aspects,
This could be a useful feature for many other use cases including versioning the data based on any updates to the mongo document.
We shall see MongoDB shell CLI example to perform the same.
The below query used and explained is just for demonstration purposes, however, the concept can be used for any of your custom query requirements.
Let’s use the below sample JSON document. We will update the document for one of the fields in the array i.e. ‘orderNumber‘. Once updated successfully, we will return the document that got updated.
{
"userId": "12345",
"orderNumber": "100",
"Name": "Categories",
"Books": [
{
"name": "C# Book",
"catId": "5555",
},
{
"name": "Typescript Book",
"catId": "44444",
}
],
"orderDate":"2020-09-20T21:07:42.313+00:00"
}
In the above example, we shall concentrate on the orderNumber fields which we want to increment by counter 1 every time I receive a book order.
Below is a basic skeleton code to establish the connection to the Database using the MongoDB
Step1- Establish the connection to the Database using MongoDB
Step2- Make your database as current
MongoDB Auto increment fields
MongoDB Autoincrement fields can be done using the $
inc
operator on a field.
Command
db.Books.update({userid:123456}, { $inc: { ‘orderNumber’:1} })
Example
Query explained,
- userid field will be matched with the input userId as filter criteria.
- $inc with options updates the document and increment the field “orderNumber” with incremental value of count 1.
- Result shows if the document is upserted or modified
Guidelines
- The
$inc
operator update or insert the fields as required. If the field does not exist,$inc
creates the field and sets the field to given value. - Accepts positive and negative values.
$inc
operator on a field with a null value might generate an error.- $inc let perform operation as atomic operation for given single document update.
After successful execution of the query, we shall see the document is updated with a new order number successfully.
References:
Do you have any comments or ideas or any better suggestions to share?
Please sound off your comments below.
Happy Coding !!
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.