Open In App

Querying in NoSQL

Last Updated : 05 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

NoSQL is termed non-SQL. We won’t use SQL to write queries in No SQL. It is not relational but it gives us an organized way of storing data. The data is stored in the form of documents rather than tabular form. The best example for NoSql is Mongo DB. In SQL we will use the term key-value pairs but in Mongo DB we will use field-value pairs. Documents are stored and the group of documents is called “Collection”. The document will be in JSON format. The data is called a “Document” and the collection of documents is called a “Collection”.

Steps to query in Mongo DB:

  • Install the MongoDB installer.
  • Specify a custom directory for mongo.
  • After installation runs the Mongo DB daemon.
  • Connect to Mongo shell.
  • You can start to code.

Querying in NoSQL:

Suppose we want to get specific results on the transport database.

{
"Brand":"Benz"
"Max_Speed":250
"Color":"Green"
}

  1. To display the vehicles which have a speed greater than 100.

Query:

>db.transport.find({Max_speed:
 {$gt:100}}).pretty()

Output:

{
"Brand":"Benz"
"Max_Speed":250
"Color":"Green"
}

2. To display the vehicles which have a speed equal to 250.

Query:

>db.transport.find({Max_speed:
 {$eq:250}}}.pretty()

Output:

{
"Brand":"Benz"
"Max_Speed":250
"Color":"Green"
}

$eq – This operator is used to check 2 values and returns the data which is equal to the specified value. So like this, we have $gte ( greater than or equal to ), $lte ( lesser than or equal to ), $lt( less than ), $ne( Not equal ) in NoSQL.

3. To display the vehicles which have a speed lesser than 500 and brand as Benz.

To write this query we need (and) operator.

Query:

>db.transport.find({$and:
[{Max_speed:{$lt:500}},{Brand:
 {$eq:"Benz"}}}.pretty()}]})

So the output will be the data where the brand is Benz and also the max_speed will be less than 500.

Output:

{
"Brand":"Benz"
"Max_Speed":250
"Color":"Green"
}

Insertion in NoSql

In MongoDB, there is no command to create a database. When we save the file the DBMS automatically creates a database. Here we use the transport database.

> use transport

So let’s insert a data of brand as Hyundai, max_speed as 100, and color as blue.

Query:

db.transport.insert({"Brand":"Hyundai"},
{"Max_speed":100},{"Color":"blue"})

Output:

WriteResult({ "nInserted": 2})

Selection in NoSql

We have inserted the data and we need to see the whole collection so the command is:

Query:

>db.transport.find()

Output:

{
"Brand":"Benz"
"Max_Speed":250
"Color":"Green"
}
{
"Brand":"Hyundai"
"Max_Speed":100
"Color":"Blue"
}

These are basic queries in NoSql.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads