MongoDB Queries Tutorial

Understanding most frequently used queries in MongoDB.

Danish Siddiq
tajawal
4 min readSep 30, 2019

--

In the Part-III of this series, we covered downloading, installing and configuring MongoDB. Now we are going to highlight the following areas:

  1. Database creation
  2. CRUD Queries
  3. Indexing
Most of the applications have these queries

Follow the steps to practice queries in Studio 3T:

  1. Connect to local MongoDB server from Studio 3T
Connect to the local server

2. Right-click on the server node in the left panel, and Select IntelliShell options to write queries

Open IntelliShell command to write queries

All following operations are possible through multiple solutions but the results differ slightly. Results for every single query appears at the bottom after execution.

1. Database Creation:

There are two ways to create a database, later one is more simple:

  • Solution I:
use online-business;
db.runCommand( { create: "products" } );

Observation:

If a database does not exist then “use” creates on the second command execution, which also produces “products” collection.

Benefits:

Multiple options are available at the time of creation, some of them are:

  1. Validator, validation level, and validation actions can be applied
  2. Size and max number of documents are possible to be defined, where size has precedence over the max number.
  3. A pipeline is available, we will explore pipeline in the next article.
  • Solution II:

This is a widely accepted, frequently used and an easy one:

use online-business;
db.products.insert
(
{
"name" : "iPhone 11 Pro",
"description" : "A simple cell with next level marketing",
"price": 500
}
)
  • Solution III:
use online-business;
db.products.insertOne
(
{
"name" : "iPhone 11 Pro",
"description" : "A simple cell with next level marketing",
"price": 500
}
)

2. CRUD:

A. Insert multiple documents:

  • Solution I:
db.products.insert
(
[ // array of documents
{
"name": "iPhone 11",
"description": "Cell with lot of cameras",
"price": 400
},
{
"name": "samsung galaxy s10",
"description": "A good option with mid range budget",
"price": 350
},
{
"name": "Huawei mate 20 pro",
"description": "Worth the money",
"price": 300
}
]
)
  • Solution II:
db.products.insertMany
(
[
{
"name": "iPhone 11",
"description": "Cell with lot of cameras",
"price": 400
},
{
"name": "samsung galaxy s10",
"description": "A good option with mid range budget",
"price": 350
},
{
"name": "Huawei mate 20 pro",
"description": "Worth the money",
"price": 300
}
]
)

B. Read:

Single document:

  • The following query returns one document.
db.products.findOne({ name: "iPhone 11 Pro" });
  • This query, on the other hand, returns “null” since Nokia is not in products. Poor Nokia, that was my first cell brand : (
db.products.findOne({ name: "Nokia" });
  • Let’s fetch a document where the price is greater than or equal to 350
db.getCollection("products").findOne({ price: { $gte: 350 } });

Although there are 2 items with a price greater than 350, findOne return one document which satisfies the query criteria.

Multiple Documents:

  • Let’s fetch documents where the price is greater than or equal to 350
db.getCollection("products").find({ price: { $gte: 350 } })

Instead of “findOne” in the above query, “find” is used to pull all documents matching the search criteria.

All documents:

  • Simply omit query parameters:
db.getCollection("products").find();

Projection:

  • If selective fields are desired in the result, then use projection in the query:
db.products.findOne({ name: "iPhone 11" }, { description: true });
  • The following query will also omit “_id” from the result set:
db.getCollection("products")
.find(
{ price: { $gte: 350 } },
{ _id: false, name: true, description: true } // projection
);

C. Update:

Single document:

The first parameter defined the search criteria, then the second parameter contains fields with updated values:

db.getCollection("products")
.update(
{ name: "iPhone 11 Pro" },
{ $set: { price: 550 } }
);

Multiple documents:

  • Solution I:
db.getCollection("products")
.update(
{ price: { $gte: 350 } },
{ $set: { expensive: true } },
{ multi: true }
);

Above query also shows that it is not necessary for the update to modify existing fields but the addition of new fields is possible.

  • Solution II:
db.getCollection("products")
.updateMany(
{ price: { $gte: 350 } },
{ $set: { "expensive": true }
}
);

Upsert:

If a query does not fetch any document then insert a new document, it is achievable by enabling “upsert” to “true” in the third parameter:

db.getCollection("products")
.update(
{ name: 'Xiaomi Black Shark 2' },
{ $set:
{
"name" : "Xiaomi Black Shark 2",
"description" : "Cell with multiple features",
"price" : 375.0
}
},
{ upsert: true }
);

D. Delete

Single document:

db.getCollection("products")
.remove(
{ price: { $gt: 800 } },
{ justOne: true }
)

Multiple documents:

If the second parameter is not provided then by default “justOne ” is treated false and all matching items delete:

db.getCollection("products")
.remove(
{ price: { $gt: 800 } }
)

All documents:

db.getCollection("products").remove()

3. Indexing:

MongoDB provides an easy way of creating indexes on text fields which results in better query execution time. Let’s create an index on the “name” field:

db.products.createIndex(
{
name: "text"
}
)

Creating an index on a field other than text is possible among other options, creating an index on price just for illustration purpose is easy:

db.products.createIndex(
{ price: 1 }
)

Conclusion:

We covered some of the basic queries. In the next article, queries to search in a text through regex and some other advanced options will be explored.

--

--