MongoDB ObjectId | MongoDB Atomic Operations (Models & Commands)

post

Today, we will explore MongoDB ObjectId using the driver’s ObjectId constructor and static methods.

What is MongoDB ObjectId?

In MongoDB, ObjectId is the default primary key used for documents and typically appears in the _id field of an inserted document. Here’s a quick example:

{  "_id": ObjectId("54759eb3c090d83494e2d804") } 

An ObjectId is a 12-byte binary BSON type and is generated using a default algorithm. These 12 bytes consist of:

SizeDescription
4 bytesA 4-byte value representing the seconds since the Unix epoch
3 bytesA 3-byte machine identifier
2 bytesA 2-byte process id
3 bytesA 3-byte counter starting with a random value

Example:

var ObjectId = require('mongodb').ObjectID; var id = new ObjectId(); console.log(id);

This will print a hexadecimal string representing the generated 12-byte ObjectId.

We can also define a custom 12-byte ObjectId:

var ObjectId = require('mongodb').ObjectID; var id = new ObjectId("aaaaaaaaaaaa"); console.log(id);

This will output the hexadecimal equivalent: 616161616161616161616161.

Driver ObjectId Constructor Methods

The driver provides different ways to create ObjectIds. You can either pass a 12-byte string, a 24-character hexadecimal string, or allow automatic generation.

Examples:

var ObjectId = require('mongodb').ObjectID; var id1 = new ObjectId(); // Auto-generated ObjectId var id2 = new ObjectId("aaaaaaaaaaaa"); // 12-byte string var id3 = new ObjectId("616161616161616161616161"); // 24-hexadecimal string 

Passing back ObjectIds from web applications is one of the common use cases.

Driver ObjectId Static Methods

Static methods make it easier to explicitly create different types of ObjectIds.

Examples:

var ObjectId = require('mongodb').ObjectID; var id1 = ObjectId.createPk(); // Create a new instance var id2 = ObjectId.createFromTime(5000); // Create ObjectId from a specific timestamp var id3 = ObjectId.createFromHexString("616161616161616161616161"); // Create ObjectId from hex string 

Driver ObjectId Instance Methods

Some useful instance methods on ObjectId are:

i. getTimestamp()

Returns the date and time based on the timestamp part of the ObjectId.

var ObjectId = require('mongodb').ObjectID; var id = new ObjectId(); console.log(id.getTimestamp());

ii. toHexString()

Converts the ObjectId to a hexadecimal string.

var ObjectId = require('mongodb').ObjectID; var id = new ObjectId("aaaaaaaaaaaa"); console.log(id.toHexString());

iii. On Buffers

You can create an ObjectId from a buffer:

var ObjectId = require('mongodb').ObjectID; var id = new ObjectId(new Buffer("aaaaaaaaaaaa").toString()); console.log(id.toHexString());

What are MongoDB Atomic Operations?

MongoDB does not support multi-document transactions (in earlier versions), but it guarantees atomic operations on single documents. This means if a document contains thousands of fields, an update operation will either update all fields or none at all.

To maintain atomicity, it is advised to group frequently updated related data into a single document.

Model Data for Atomic Operations

Example document:

{   "_id": 1,   "product_name": "ABC",   "category": "books",   "product_total": 5,   "product_available": 3,   "product_bought_by": [     { "customer": "j", "date": "7-Jan-2019" },     { "customer": "m", "date": "8-Jan-2019" }   ] } 

When a customer tries to buy a product, we check the product_available field. If available, we decrease the count and add the customer's purchase details—all in a single atomic operation.

Command:

db.examples.findAndModify({  query: { _id: 2, product_available: { $gt: 0 } },  update: {    $inc: { product_available: -1 },    $push: { product_bought_by: { customer: "r", date: "9-Jan-2019" } }  } })

Since this update is done with a single query, atomicity is preserved.

Commonly Used Commands for MongoDB Atomic Operations

$Set – Sets a field to a specified value.
{ $set: { field: value } }

$Unset – Removes a field.
{ $unset: { field: 1 } }

$Inc – Increments or decrements a field by a given value.
{ $inc: { field: value } }

$Push – Adds an element to an array.
{ $push: { field: value } }

$Pull – Removes elements from an array that match a condition.
{ $pull: { field: value } }

$Pop – Removes the first or last element of an array.
{ $pop: { field: 1 } }

$Rename – Renames a field.
{ $rename: { old_field_name: new_field_name } }

$Bit – Performs bitwise operations on integer values.
{ $bit: { field: { and: 5 } } }

Summary

In this tutorial, we learned about MongoDB ObjectId and its construction methods, instance methods, and static methods. We also discussed MongoDB atomic operations, how to structure data models to ensure atomicity, and the common update commands used for atomic operations.


Share This Job:

Write A Comment

    No Comments