MongoDB ObjectId, How to get lowercase hexadecimal string from MongoDB ObjectId() – Mongodb Objectid Operations, What is MongoDB ObjectId() ? ObjectIds are small unique ID that generated very fast and ordered. ObjectId values consist of 12 bytes, where the first four bytes are a timestamp that reflect the seconds since the Unix epoch, 5-byte random value, and last 3-byte counter, starting with a random value.

What is MongoDB ObjectId() ?

ObjectIds are small unique ID that generated very fast and ordered. ObjectId values consist of 12 bytes, where the first four bytes are a timestamp that reflect the seconds since the Unix epoch, 5-byte random value, and last 3-byte counter, starting with a random value.

In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field.

MongoDB ObjectId is generated by MongoDB Drivers and the Server using a default Algorithm. By default typeof MongoDB ObjectId is object.

MongoDB ObjectId 12 bytes can be break up in to following:

Size Description
4 Bytes 4-byte value representing the seconds since the Unix epoch
3 Bytes 3-byte machine identifier
2 Bytes 2-byte process id
3 Bytes 3-byte counter, starting with a random value

Above is a description of MongoDB ObjectId. Most of the time developers requires unique id of the objects to be rendered on web page. In MongoDB ObjectId are the primary key and best for using as unique ID. Therefore here on the progrramers.com we are giving the solution for ‘How to get lowercase hexadecimal mongodb _id string from ObjectId() in MongoDB ?

Below is the example database which we are using the MongoDB tutorial :



> db.cars.find().toArray();
[
{
"_id" : ObjectId("5d53065a520ea88ac000e981"),
"name" : "Ford",
"color" : "blue",
"weight" : "300KG"
},
{
"_id" : ObjectId("5d53066a520ea88ac000e982"),
"name" : "Opel",
"color" : "red"
},
{
"_id" : ObjectId("5d530677520ea88ac000e983"),
"name" : "Mustang",
"color" : "silver"
},
{
"_id" : ObjectId("5d53069f520ea88ac000e984"),
"name" : "porsche",
"color" : "black"
}
]
>


There are many methods available that can be use to extract the lowercase hexadecimal mongodb _id string from MongoDB ObjectId. We will try to approach all possible ways by using MongoDB methods and JavaScript methods as well.

How to get lowercase hexadecimal string from MongoDB ObjectId using ‘valueOf()’ method

Syntax : db.collectionname.findOne()._id.valueOf()

> db.cars.findOne()._id.valueOf();
5d53065a520ea88ac000e981
>


Explanation

In this method first db.collectionname.findOne() will return the JavaScript Object in form of ‘property : value’ pair then by using JavaScript Object. Property method we will get ObjectId() e.g. ‘ObjectId("5d53065a520ea88ac000e981")’. After that valueOf() function extract the lowercase hexadecimal MongoDB _id string e.g. ‘5d53065a520ea88ac000e981’ from MongoDB ObjectId(). The data-type of the result will be ‘string’.

How to get lowercase hexadecimal string from MongoDB ObjectId using ‘str’ method


Syntax : db.collectionname.findOne()._id.str

> db.cars.findOne()._id.str;
5d53065a520ea88ac000e981
>


Explanation

In this method first db.collectionname.findOne() will return the JavaScript Object like above mentioned method e.g. ‘ObjectId("5d53065a520ea88ac000e981")’. After that ‘str’  method extract the lowercase hexadecimal mongodb _id string e.g. ‘5d53065a520ea88ac000e981’ from MongoDB ObjectId(). The data-type of the result will be ‘string’.

How to get value of the ObjectId() in MongoDB using stored functions


There is a special system collection named system.js that can store JavaScript functions for reuse. We can latter call the function using ‘db.eval()’ or ‘db.loadServerScripts()’ methods and get results.

Syntax : db.system.js.save({_id:”functionname”,value:function(parameters){//code here}})

> db.system.js.save({
... _id:"getObjectID",
... value:function(){
... var doc = db.cars.findOne();
... return doc._id.valueOf();
... }
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.eval("return getObjectID()")
WARNING: db.eval is deprecated
5d53065a520ea88ac000e981
>

Explanation

Below example first stores the object in ‘doc’ variable in form of ‘property: value’ pair then by using JavaScript Object. Property method we will get ObjectId() e.g. ‘ObjectId("5d53065a520ea88ac000e981")’. After that valueOf() function extract the lowercase hexadecimal MongoDB _id string e.g. ‘5d53065a520ea88ac000e981’ from MongoDB ObjectId(). The data-type of the result will be ‘string’. The whole function expression stored in variable and saved in ‘system.js’ collection.
Note : db.eval is deprecated from MongoDB version 3.2 but finally db.eval is removed from MongDB version 4.2 but db.loadServerScripts() method can be used instead

Above stored function is called using ‘db.eval()’ method, below is another method to call stored function in MongoDB shell.

> db.system.js.save({
... _id:"getObjectID",
... value:function(){
... var doc = db.cars.findOne();
... return doc._id.valueOf();
... }
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.loadServerScripts()
> getObjectID()
WARNING: db.eval is deprecated
5d53065a520ea88ac000e981
>



How to get value of the ObjectId() in MongoDB using plain JavaScript

MongoDB stored functions uses pure JavaScript so it is possible to apply various JavaScript methods to perform a certain task. Now we will see how to get the hexadecimal string in bulk using ‘Array.map()’ function from JavaScript Arrary of ObjectId().


> db.system.js.save({
... _id:"getObjectID",
... value:function(){
... var doc = db.cars.find().toArray();
... return doc.map(function(i){return i._id.valueOf()});
... }
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.eval("return getObjectID()");
WARNING: db.eval is deprecated
[
"5d53065a520ea88ac000e981",
"5d53066a520ea88ac000e982",
"5d530677520ea88ac000e983",
"5d53069f520ea88ac000e984"
]
>


How to get value of the ObjectId() in MongoDB using forEach loop

In this example we will see how to use forEach loop in MongoDB Stored function to extract hexadecimal MngoDB _id string in bulk from JavaScript Arrary of ObjectId().


> db.system.js.save({
... _id:"getObjectID",
... value:function(){
... var doc = db.cars.find().toArray();
... var myArr = [];
... doc.forEach(element => {
... myArr.push(element._id.valueOf());
... });
... return myArr;
... }
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.eval("return getObjectID()");
WARNING: db.eval is deprecated
[
"5d53065a520ea88ac000e981",
"5d53066a520ea88ac000e982",
"5d530677520ea88ac000e983",
"5d53069f520ea88ac000e984"
]
>


How to get value of the ObjectId() in MongoDB using for Loop

In this example we will see how to use for loop in MongoDB Stored function to extract hexadecimal MongoDb _id string in bulk from JavaScript Arrary of ObjectId().


> db.system.js.save({
... _id:"getObjectID",
... value:function(){
... var doc = db.cars.find().toArray();
... var myArr = [];
... for(var i=0;i<doc.length;i++){
... myArr.push(doc[i]._id.valueOf());
... }
... return myArr;
... }
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.eval("return getObjectID()");
WARNING: db.eval is deprecated
[
"5d53065a520ea88ac000e981",
"5d53066a520ea88ac000e982",
"5d530677520ea88ac000e983",
"5d53069f520ea88ac000e984"
]
>


Mongodb compare Objectid to String



> typeof db.cars.findOne().toString();
string
>


How to get value of the ObjectId() in MongoDB using JavaScript substring

In this example we will see how to use JavaScript substring method in MongoDB Stored function to extract hexadecimal MongoDB _id string from ObjectId().


> db.system.js.save({
... _id:"getObjectID",
... value:function(){
... var doc = db.cars.findOne();
... return doc._id.toString().substring(10, 34);
... }
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.eval("return getObjectID()");
WARNING: db.eval is deprecated
5d53065a520ea88ac000e981
>


Same method can be used to extract hexadecimal MongoDB _id string in bulk from JavaScript Arrary of ObjectId().


> db.system.js.save({
... _id:"getObjectID",
... value:function(){
... var doc = db.cars.find().toArray();
... return doc.map(function(i){
... return i._id.toString().substring(10, 34)
});
... }
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.eval("return getObjectID()");
WARNING: db.eval is deprecated
[
"5d53065a520ea88ac000e981",
"5d53066a520ea88ac000e982",
"5d530677520ea88ac000e983",
"5d53069f520ea88ac000e984"
]
>


How to get value of the ObjectId() in MongoDB using JavaScript slice

In this example we will see how to use JavaScript slice method in MongoDB Stored function to extract hexadecimal MongoDb _id string from ObjectId().


> db.system.js.save({
... _id:"getObjectID",
... value:function(){
... var doc = db.cars.findOne();
... return doc._id.toString().slice(10, 34);
... }
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.eval("return getObjectID()");
WARNING: db.eval is deprecated
5d53065a520ea88ac000e981
>


Same method can be used to extract hexadecimal string in bulk from JavaScript Arrary of ObjectId().


> db.system.js.save({
... _id:"getObjectID",
... value:function(){
... var doc = db.cars.find().toArray();
... return doc.map(function(i){
... return i._id.toString().slice(10, 34)
});
... }
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.eval("return getObjectID()");
WARNING: db.eval is deprecated
[
"5d53065a520ea88ac000e981",
"5d53066a520ea88ac000e982",
"5d530677520ea88ac000e983",
"5d53069f520ea88ac000e984"
]
>


How to get typeof the ObjectId() in MongoDB using JavaScript

Getting the typeof ObjectId()


> typeof db.cars.findOne()._id;
object
>


How to get the typeof function variable stored in system.js



> typeof db.eval("return getObjectID()");
WARNING: db.eval is deprecated
object
>

How to get the typeof output value



> typeof db.eval("return getObjectID()")[0];
WARNING: db.eval is deprecated
string
>


Related Topics


progrramers-logo

progrramers

Hello friends! Progrramers is a tutorial site of w3 programming. If you like this tutorial site please encourages us by sharing this site links with your friends and nears & dears who want to learn web development and give us like on our Facebook page. If have any question please type in to comment box or send us message on social media sites via below given social links. Thank you, have a nice learning.

Post A Comment:

18 comments:

  1. This is how we can get the lowercase hexadecimal mongodb _id string from ObjectId() in MongoDB. Hope you will enjoy learning with this post and get something useful. I with progrramers.com always trying to do lot better in web technologies. If you have any query or suggestions please share with us. Progrramers.com and me is always waiting for you. Thank You!

    ReplyDelete
  2. Hey, thanks for this great article I really like this post and I love your blog and also Check Analytics Training In 360DIGITMG Analytics Training certification program provides an overview of how Python and R programming can be employed in Data Mining of structured (RDBMS) and unstructured (Big Data) data. Comprehend the concepts of Data Preparation, Data Cleansing and Exploratory Data Analysis. Perform Text Mining to enable Customer Sentiment Analysis. Learn Machine learning and developing Machine Learning Algorithms for predictive modeling using Regression Analysis. Assimilate various black-box techniques like Neural Networks, SVM and present your findings with attractive Data Visualization techniques.
    360Digitmg Analytics Training institute

    ReplyDelete
  3. Nice post keep up the good work gained great knowledge. Wating for the next blog update thank you.

    data science course in chennai

    Artificial Intelligence course in chennai

    ReplyDelete
  4. Hey, thanks for this great article I really like this post and I love your blog and also Check machine learning course in hyderabad at 360DIGITMG.
    360Digitmg machine learning course in hyderabad

    ReplyDelete
  5. Nice post keep up the good work,gained great knowledge. Wating for the next blog update. thank you
    Data-science course in chennai

    ReplyDelete
  6. Excellent Blog! I would like to thank for the efforts you have made in writing this post. I am hoping the same best work from you in the future as well. I wanted to thank you for this websites! Thanks for sharing. Great websites!
    360Digitmg Python Training institute

    ReplyDelete
  7. This is my first time i visit here. I found so many interesting stuff in your blog especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the enjoyment here keep up the good work hex to decimal conversion

    ReplyDelete
  8. Really nice and interesting post. I was looking for this kind of information and enjoyed reading this one. Keep posting. Thanks for sharing.

    data science training in vizag

    ReplyDelete
  9. Really nice and interesting post. I was looking for this kind of information and enjoyed reading this one. Keep posting. Thanks for sharing.

    data science using python and r programming vizag

    ReplyDelete
  10. This is an excellent post I seen thanks to share it. It is really what I wanted to see hope in future you will continue for sharing such a excellent post.360DigiTMG data science course in malaysia

    ReplyDelete
  11. Extraordinary post I should state and a debt of gratitude is in order for the data. Instruction is unquestionably a clingy subject. Be that as it may, is still among the main subjects within recent memory. I value your post and anticipate more.data science course in delhi

    ReplyDelete
  12. Thanks for sharing the valuable information. it’s really helpful.Best data science courses in hyerabad

    ReplyDelete
  13. https://360digitmg.com/data-analytics-certification-training-course-in-hyderabad

    ReplyDelete
  14. Thanks for the information about Blogspot very informative for everyone
    data science course in gurgaon

    ReplyDelete
  15. Going to graduate school was a positive decision for me. I enjoyed the coursework, the presentations, the fellow students, and the professors. And since my company reimbursed 100% of the tuition, the only cost that I had to pay on my own was for books and supplies. Otherwise, I received a free master’s degree. All that I had to invest was my time.
    data scientist course

    ReplyDelete