MongoDB

MongoDB Search by ID Example

1. Introduction

This is an in-depth article on how to search by ID in the MongoDB. MongoDB is an open-source NoSQL database. Mongo Database is based in C++ language. In this article, we discuss the MongoDB concepts related to querying by Id in a scalable and performance-oriented Mongo database.

2. MongoDB Search by ID

2.1 Prerequisites

MongoDB needs to be installed for the MongoDB Search by ID example.

2.2 Download

You can download the Mongo DB from the Mongo Database website for linux, windows or macOS version.

2.3 Setup

On MacOS, you need to tap the formula repository of MongoDB. This repo needs to be added to the formula list. The command below adds the formula repository of MongoDB to the formula list:

Brew Tap

brew tap mongodb/brew

After setting the formula list, you can install the Mongo DB with the following command :

Brew Tap

brew install mongodb-community@4.0

2.4 MongoDB CommandLine

After installation, you can run MongoDB on the command line. To run mongoDB on the command line, the following command can be used:

Mongod CommandLine

mongod --config /usr/local/etc/mongod.conf

The output of the executed command is shown below.

MongoDB Search by ID - Command Line
Mongod Command Line

2.5 Mongo Shell

After starting the Mongod process, Mongo Shell can be invoked on the command line. Mongo shell can be run using the command below:

Mongod Shell

mongo

The output of the executed command is shown below.

MongoDB Search by ID - Mongo Shell
Mongo Shell

2.6 Find By Id

2.6.1 Create Database

You can use database_name to create a database. This command will create a new database. If the database exists, it will start using the existing database. The command below is used to create “insights” database:

Create Database

use insights

The output of the executed command is shown below.

MongoDB Search by ID - Create Database
Create Database

The output does not show insights in the database. This is because insights does not have any collection.

2.6.2 Create Collection

You can use createCollection command to create a set of documents. The created collection is used to create a document. The command below is used to create “persons” collection:

Create Database

db.createCollection("persons")

The output of the executed command is shown below.

MongoDB Search by ID - Create Collection
Create Collection

The output now shows the database insights in the list of databases.

2.6.3 Create a Document

You can use the insertOne method to create a document which is stored in the collection. A new collection will be created if the collection does not exist in the database. The document will be inserted into the collection after it is created. In the command, if _id parameter is not specified, then a unique ObjectId is assigned for the document.

The command below is used to create a person document:

Create Person

db.persons.insertOne(
   { person: "paul smith", id: 002, ssn: 324675431,gender: "male" }
)

db.persons.find().pretty()

The output of the executed command is shown below.

MongoDB Search by ID - Create Document
Create Document

The find() method on the collection persons is invoked to find the documents in the collection. pretty() method prints the documents in a formatted way.

2.6.4 Find

In the above output, the person document has the _id equal to objectId 5cd68b56e5d2567eb32b841b. You can use find method to search by _id using the command below:

Find by _id

db.persons.find( { "_id": ObjectId("5cd68b56e5d2567eb32b841b") } )

The output of the executed command is shown below.

MongoDB Search by ID - Find by Id
Find by Id

2.6.5 Find – Query Operators

You can find multiple documents by _id using find method and query operators. The command used is shown below:

Find by Query Operators

db.persons.insertOne(
   { person: "will smith", id: 004, ssn: 624675431,gender: "male" }
)

db.persons.find( { "_id": { $in:[ObjectId("5cd68b56e5d2567eb32b841b"),ObjectId("5cd69f69e5d2567eb32b841d")] } }).pretty()

The output of the executed command is shown below.

MongoDB Search by ID - Find by Query
Find by Query

2.6.6 Find- Range Operators

You can find multiple documents by _id using find method and range operators $lt and $gt. The command used is shown below:

Find by Range Operators

db.persons.insertOne(
   { person: "Richard More", _id: 1, ssn: 224675431,gender: "male" }
)

db.persons.find( { "_id": { $lt:3,$gt:0} } ).pretty()

The output of the executed command is shown below.

MongoDB Search by ID - Range
Find – Range

2.6.6 FindOne

You can find by _id using findOne() method on the collection. The command used is shown below:

FindOne by _id

db.persons.find( { "_id": ObjectId("5cd68b56e5d2567eb32b841b") } )

The output of the executed command is shown below.

FindOne Method

2.6.7 FindAndModify

You can use findAndModify method to update the document after finding the document by _id. The command used is shown below:

FindAndModify method

db.persons.insertOne(
   { person: "brad smith", id: 003, ssn: 454675431,gender: "male" }
)

db.persons.findAndModify({
    query: { "_id": ObjectId("5cd694ace5d2567eb32b841c") },
    sort: { "id": 1 },
    update: { $inc: { "ssn": 1 } },
    upsert: true
})

The output of the executed command is shown below.

Find And Modify

2.6.8 FindOneAndDelete

You can use findOneAndDelete method to find the document by _id and delete it. The command used is shown below:

FindOneAndDelete Method

db.persons.findOneAndDelete(
   { "_id": ObjectId("5cd694ace5d2567eb32b841c") }
)

The output of the executed command is shown below.

FindOneAndDelete

2.6.9 FindOneAndReplace

You can use findOneAndReplace method to find the document by _id and replace it. The command used is shown below:

FindOneAndReplace Method

db.persons.findOneAndReplace(
   { "_id": ObjectId("5cd68b56e5d2567eb32b841b") },
   { "ssn": 323455678 }
)
db.persons.find().pretty()

The output of the executed command is shown below.

FineOneAndReplace Method

2.6.10 FindOneAndUpdate

You can use findOneAndUpdate method to find the document by _id and update it. The command used is shown below:

FindOneAndReplace Method

db.persons.findOneAndUpdate(
   { "_id": ObjectId("5cd68b56e5d2567eb32b841b") },
   { $inc: { "ssn" : 7 } }
)
db.persons.find().pretty()

The output of the executed command is shown below.

FindOneAndUpdate Method

2.7 Best Practices

Best practices of MongoDB Operations can be obtained from this link. The best practices of MongoDB performance can be accessed from the MongoDB website.

2.8 Error Handling

Programming with Java using MongoDB is available on java code geeks at this link. MongoException is the main parent exception class in MongoDB. MongoException.CursorNotFound is the exception related to Cursor not found. Timed out error can happen if the time out is not appropriately configured. The default for time out for finding the cursor is 10 minutes. MongoException.Network exception is related to error in network. You can set the networking configuration for retry, number of retries and time to wait for a retry.

3. Download the Source Code

Download
You can download the full source code of this example here: MongoDB Search by ID Example

Bhagvan Kommadi

Bhagvan Kommadi is the Founder of Architect Corner & has around 20 years’ experience in the industry, ranging from large scale enterprise development to helping incubate software product start-ups. He has done Masters in Industrial Systems Engineering at Georgia Institute of Technology (1997) and Bachelors in Aerospace Engineering from Indian Institute of Technology, Madras (1993). He is member of IFX forum,Oracle JCP and participant in Java Community Process. He founded Quantica Computacao, the first quantum computing startup in India. Markets and Markets have positioned Quantica Computacao in ‘Emerging Companies’ section of Quantum Computing quadrants. Bhagvan has engineered and developed simulators and tools in the area of quantum technology using IBM Q, Microsoft Q# and Google QScript. He has reviewed the Manning book titled : "Machine Learning with TensorFlow”. He is also the author of Packt Publishing book - "Hands-On Data Structures and Algorithms with Go".He is member of IFX forum,Oracle JCP and participant in Java Community Process. He is member of the MIT Technology Review Global Panel.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button