Can we work MongoDB findOne() with long type _id?


Yes, we can do that using the NumberLong() datatype in MongoDB. Let us create a collection with documents −

> db.demo618.insertOne({_id:NumberLong("6336366454"),Name:"Chris"});
{ "acknowledged" : true, "insertedId" : NumberLong("6336366454") }
> db.demo618.insertOne({_id:NumberLong("6336366455"),Name:"David"});
{ "acknowledged" : true, "insertedId" : NumberLong("6336366455") }
> db.demo618.insertOne({_id:NumberLong("6336366456"),Name:"Bob"});
{ "acknowledged" : true, "insertedId" : NumberLong("6336366456") }

Display all documents from a collection with the help of find() method −

> db.demo618.find();

This will produce the following output −

{ "_id" : NumberLong("6336366454"), "Name" : "Chris" }
{ "_id" : NumberLong("6336366455"), "Name" : "David" }
{ "_id" : NumberLong("6336366456"), "Name" : "Bob" }

Following is the query to implement MongoDB findOne() with long type _id −

> db.demo618.findOne({_id: NumberLong("6336366454")});

This will produce the following output −

{ "_id" : NumberLong("6336366454"), "Name" : "Chris" }

Updated on: 12-May-2020

119 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements