MongoDB Objectid | MongoDB Atomic Operations (Models & Commands)

In the last tutorial we had learned, covered queries and analyzing queries. Now we will discuss MongoDB ObjectId with driver ObjectId constructor and static methods. Along with this, we will study about MongoDB Atomic Operations with model and commands.

MongoDB Objectidand  MongoDB Atomic Operations

MongoDB Objectid | MongoDB Atomic Operations (Models & Commands)

1. What is MongoDB ObjectId?

ObjectId is the default primary key for a MongoDB document and is usually found in the _id field in an inserted document. Let’s take an example to understand this.

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

It is a 12-byte binary BSON type that contains any 12 bytes. To generate MongoDB ObjectId, we will be using a default algorithm. An ObjectId’s 12 bytes will then contain the following:

SizeDescription
4 bytes
A 4-byte value representing the seconds
since the Unix epoch
3 bytes3-byte machine identifier
2 bytes2-byte process id
3 bytes
3-byte counter, starting with a random value

Let’s take an example to understand this better.

var ObjectId = require('mongodb').ObjectID

var id = new ObjectId();
console.log(id)

It will print a hexadecimal representation of the 12 byte ObjectId the driver generated.

Do you know how can we execute MongoDB in Java Program?

Here, we will create the definition of a 12 byte ObjectId.

var ObjectId = require('mongodb').ObjectID

var id = new ObjectId("aaaaaaaaaaaa");
console.log(id)

It will print the hexadecimal value 616161616161616161616161, which corresponds to the given string.

2. Driver ObjectId Constructor Methods

The driver allows you to create MongoDB ObjectId in many different kinds of ways. You can pass a 12-byte string or a 24-byte hexadecimal representation and arguments as well.

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

Now, it creates a new generated ObjectId using the algorithm outlined above.

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

Now, creates a new specific MongoDB ObjectId12-byte12 byte string.

var ObjectId = require('mongodb').ObjectID
var id = new ObjectId("616161616161616161616161");

It is useful for passing back Id’s from a web application.

3. Driver ObjectId Static Methods

This is meant to be helpful in making it more explicit what your intention is when creating a new ObjectId in MongoDB.

var ObjectId = require('mongodb').ObjectID
var id = ObjectId.createPk();

Recommended reading – MongoDB Relationships and Database Reference

Now, we will create a new instance.

var ObjectId = require('mongodb').ObjectID
var id = ObjectId.createFromTime(5000);

Now, creating an ObjectId from a second timestamp.

var ObjectId = require('mongodb').ObjectID
var id = ObjectId.createFromHexString("616161616161616161616161");
Driver ObjectId Instance methods

Some static methods on a MongoDB ObjectId instance are the following:

  • getTimestamp()
  • toHexString()
  • On Buffers
Driver ObjectId Static Methods in MongoDB

Driver ObjectId Static Methods

i. getTimestamp()

var ObjectId = require('mongodb').ObjectID

var id = new ObjectId();
console.log(id.getTimestamp())

It returns a date object representing the timestamp part of the 12 byte ObjectId as defined by the above algorithm.

Have a look – MongoDB Text Search on Single & Multiple Fields

ii. toHexString()

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

This prints the hexadecimal representation of the ObjectId.

iii. On Buffers

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

After converting buffer into its string representation we can correctly create a new ObjectId.

4. What is MongoDB Atomic Operations?

MongoDB does not provide atomic transactions on multiple documents, but it provides atomic operations on single documents. So, if a document is having thousands of fields then it will either update all or none. To maintain atomicity in MongoDB, we should keep all related information which is frequently updated together in a single document. This makes sure that all updates for a single document are atomic.

5. Model Data for Atomic Operations

{
   "_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"
      }
   ]
}

Here, we have added information of the customer who buys a product in the product_brought_by field. If a customer wants to buy something then we will check it’s availability at a product_available field. If it is available then we will then we will reduce the value as well as insert a new customer. For doing this operation we will use a findAndModify 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"}} 
   } 
})

Our approach makes sure that the product purchase information is updated only when the product is available. And as the whole transaction is in one query it leads to atomicity.

16 Different Types of MongoDB Data Types

Some Commonly Used Commands in MongoDB atomic operations:

  • $Bit
  • $Rename
  • $Pop
  • $Pull
  • $Push
  • $Inc
  • $Unset
  • $Set
 Commands in MongoDB atomic operations

Commands in MongoDB atomic operations

Now, let’s see the details of these commands in MongoDB atomic operations.

i. $Set

It is used to specify a key and update the key.

{ $set : { field : value } }

ii. $Unset

Remove a key.

{ $unset : { field : 1} }

iii. $Inc

Numeric value of the document keys to increase or decrease operations.

{ $inc : { field : value } }

Do you know how projection in MongoDb affects performance?

iv. $Push

It is used to add values to fields.

{ $push : { field : value } }

v. $Pull

To delete a field from an array.

{ $pull : { field : _value } }

vi. $Pop

Deletes first or last element.

{ $pop : { field : 1 } }

vii. $Rename

Modify the field.

{ $rename : { old_field_name : new_field_name } }

viii. $Bit

Bit operations, integer type.

{$bit : { field : {and : 5}}}

So, this was all about objectId and atomic operations in MongoDB. Hope, you liked our explanation.

6. Summary

Hence, we have studied about atomic operations and objectid in MongoDB. Along with ObjectId constructor and static methods. In addition, we studied the model of MongoDB Atomic Operations with commands.

Still, you have a doubt? Feel free to share with us!

Related Topic – Install MongoDB in 4 Min

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.