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
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!
ReplyDeleteNice post keep up the good work gained great knowledge. Wating for the next blog update thank you.
ReplyDeletedata science course in chennai
Artificial Intelligence course in chennai
Nice post keep up the good work,gained great knowledge. Wating for the next blog update. thank you
ReplyDeleteData-science course in chennai
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!
ReplyDelete360Digitmg Python Training institute
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
ReplyDeleteThank You, Keep supporting...
DeleteReally nice and interesting post. I was looking for this kind of information and enjoyed reading this one. Keep posting. Thanks for sharing.
ReplyDeletedata science training in vizag
Really nice and interesting post. I was looking for this kind of information and enjoyed reading this one. Keep posting. Thanks for sharing.
ReplyDeletedata science using python and r programming vizag
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
ReplyDeleteExtraordinary 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
ReplyDeletehttps://360digitmg.com/data-analytics-certification-training-course-in-hyderabad
ReplyDeleteThanks for the information about Blogspot very informative for everyone
ReplyDeletedata science course in gurgaon
great work
ReplyDeleteGoing 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.
ReplyDeletedata scientist course
Thanks for sharing nice information....
ReplyDeletedata science courses in aurangabad
Thanks for sharing this information. I really like your blog post very much. You have really shared a informative and interesting blog post with people..
ReplyDeletedata science training in hyderabad
Really an awesome blog and useful content. Keep update more blogs again soon. Thank you.
ReplyDeleteData Science Course in Hyderabad