Learn Node.js unit testing with Jest, using mocking, snapshots, and best practices to ensure reliable and efficient application performance.
MongoDB is a popular database management system. MongoDB is widely used NoSQL database management system in the industry. In this article, we'll learn mongoDB querying for simple and complex mongoDB queries.
MongoDB Querying helps us to perform one or multiple operations in mongodb database. MongoDB is a popular NoSQL document-oriented database that provides a flexible and scalable platform for storing and managing data.
One of the key features of MongoDB is its querying system, which enables users to users to retrieve data from the database based on various criteria or conditions. MongoDB queries are easy to use, quick and efficient in retrieving the required data.
To work with mongodb query, we will first set up MongoDB with NodeJS and insert student data to mongoDB database.
Create node project with mongodb with following command
mkdir mongodb-querying
cd mongodb-queryingnpm init -yinsertMany.js and insert students data to mongodb databaseconst { MongoClient } = require('mongodb')
// Replace the uri string with your connection string.
const uri = `mongodb://0.0.0.0:27017`
const studentList = [
{
rollNo: '1',
firstName: 'Akshay',
lastName: 'Verma',
},
{
rollNo: '2',
firstName: 'Sunil',
lastName: 'Singh',
},
{
rollNo: '3',
firstName: 'Aruni',
lastName: 'Kumari',
},
{
rollNo: '4',
firstName: 'Sikka',
lastName: 'Singh',
},
{
rollNo: '5',
firstName: 'Sonu',
lastName: 'Kumar',
},
{
rollNo: '6',
firstName: 'Maya',
lastName: 'Devi',
},
{
rollNo: '7',
firstName: 'Arun',
lastName: 'Pratap',
},
{
rollNo: '8',
firstName: 'Rahul',
lastName: 'Kumar',
},
{
rollNo: '9',
firstName: 'Suhani',
lastName: 'Sah',
},
{
rollNo: '10',
firstName: 'Akhilesh',
lastName: 'kumar',
},
]
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
const database = client.db('students_db')
database
.collection('students')
.insertMany(studentList)
.then((res) => {
console.log(res)
})
.then(() => {
client.close()
})
.catch((error) => {
console.log(error)
})node insertMany.js to insert student list into local mongodb database.find() method to fetch data from MongoDB database.find() method also accept an optional query object that helps to select certain documents from MongoDB database.students by passing an empty object to find() method:database
.collection('students')
.find({})
.toArray()
.then((res) => {
console.log(res)
client.close()
})
.catch((err) => {
console.log(err)
client.close()
})students:[
{
_id: new ObjectId("641b965964dec0176f6497c5"),
rollNo: '1',
firstName: 'Akshay',
lastName: 'Verma'
},
{
_id: new ObjectId("641b965964dec0176f6497c6"),
rollNo: '2',
firstName: 'Sunil',
lastName: 'Singh'
},
{
_id: new ObjectId("641b965964dec0176f6497c7"),
rollNo: '3',
firstName: 'Aruni',
lastName: 'Kumari'
},
{
_id: new ObjectId("641b965964dec0176f6497c8"),
rollNo: '4',
firstName: 'Sikka',
lastName: 'Singh'
},
{
_id: new ObjectId("641b965964dec0176f6497c9"),
rollNo: '5',
firstName: 'Sonu',
lastName: 'Kumar'
},
{
_id: new ObjectId("641b965964dec0176f6497ca"),
rollNo: '6',
firstName: 'Maya',
lastName: 'Devi'
},
{
_id: new ObjectId("641b965964dec0176f6497cb"),
rollNo: '7',
firstName: 'Arun',
lastName: 'Pratap'
},
{
_id: new ObjectId("641b965964dec0176f6497cc"),
rollNo: '8',
firstName: 'Rahul',
lastName: 'Kumar'
},
{
_id: new ObjectId("641b965964dec0176f6497cd"),
rollNo: '9',
firstName: 'Suhani',
lastName: 'Sah'
},
{
_id: new ObjectId("641b965964dec0176f6497ce"),
rollNo: '10',
firstName: 'Akhilesh',
lastName: 'kumar'
}
]find() to select specific documents.{ 'rollNo': '3' } to find() method.database
.collection('students')
.find({ rollNo: '3' })
.toArray()
.then((res) => {
console.log(res)
client.close()
})
.catch((err) => {
console.log(err)
client.close()
})find() method will return the document where rollNo is equal to 3:[
{
_id: new ObjectId("641d46919bcf81fbf648c599"),
rollNo: '3',
firstName: 'Aruni',
lastName: 'Kumari'
}
]MongoDB provides various query operators that allow you to specify complex selection criteria for your queries. Query operators are represented as keys in query objects, and their values specify the selection criteria. Here are some commonly used query operators:
Comparison operators allow you to compare a field to a specified value or another field. Here are some commonly used comparison operators:
$and:database
.collection('students')
.find({
$and: [
{
grade: 'A',
rollNo: { $lt: 6 },
},
],
})
.toArray()
.then((res) => {
console.log(res)
client.close()
})
.catch((err) => {
console.log(err)
client.close()
})[
{
_id: new ObjectId("641f2bcfc50d5d9eb25a554c"),
rollNo: 1,
firstName: 'Akshay',
lastName: 'Verma',
grade: 'A'
},
{
_id: new ObjectId("641f2bcfc50d5d9eb25a554f"),
rollNo: 4,
firstName: 'Sikka',
lastName: 'Singh',
grade: 'A'
}
]$ordatabase
.collection('students')
.find({
$or: [{ grade: 'A' }, { rollNo: { $lt: 6 } }],
})
.toArray()
.then((res) => {
console.log(res)
client.close()
})
.catch((err) => {
console.log(err)
client.close()
})[
{
_id: new ObjectId("641f2bcfc50d5d9eb25a554c"),
rollNo: 1,
firstName: 'Akshay',
lastName: 'Verma',
grade: 'A'
},
{
_id: new ObjectId("641f2bcfc50d5d9eb25a554d"),
rollNo: 2,
firstName: 'Sunil',
lastName: 'Singh',
grade: 'C'
},
{
_id: new ObjectId("641f2bcfc50d5d9eb25a554e"),
rollNo: 3,
firstName: 'Aruni',
lastName: 'Kumari',
grade: 'B'
},
{
_id: new ObjectId("641f2bcfc50d5d9eb25a554f"),
rollNo: 4,
firstName: 'Sikka',
lastName: 'Singh',
grade: 'A'
},
{
_id: new ObjectId("641f2bcfc50d5d9eb25a5550"),
rollNo: 5,
firstName: 'Sonu',
lastName: 'Kumar',
},
{
_id: new ObjectId("641f2bcfc50d5d9eb25a5555"),
rollNo: 10,
firstName: 'Akhilesh',
lastName: 'kumar',
grade: 'A'
}
]$and and $ordatabase
.collection('students')
.find({
courseDuration: {
math: 75,
physics: 40,
chemistry: 35,
unit: 'days',
},
})
.toArray()
.then((res) => {
console.log(res)
client.close()
})
.catch((err) => {
console.log(err)
client.close()
})[
{
_id: new ObjectId("641fdf9eb3cd59e2c505f2af"),
rollNo: 10,
firstName: 'Akhilesh',
lastName: 'kumar',
courseDuration: { math: 75, physics: 40, chemistry: 35, unit: 'days' },
grade: 'A'
}
]We can query documents using nested field and dot notation (i.e. field.nestedField)
database
.collection('students')
.find({
'courseDuration.math': 75,
'courseDuration.unit': 'days',
})
.toArray()
.then((res) => {
console.log(res)
client.close()
})
.catch((err) => {
console.log(err)
client.close()
})[
{
_id: new ObjectId("641fdf9eb3cd59e2c505f2a7"),
rollNo: 2,
firstName: 'Sunil',
lastName: 'Singh',
courseDuration: { math: 75, physics: 60, chemistry: 45, unit: 'days' },
grade: 'C'
},
{
_id: new ObjectId("641fdf9eb3cd59e2c505f2af"),
rollNo: 10,
firstName: 'Akhilesh',
lastName: 'kumar',
courseDuration: { math: 75, physics: 40, chemistry: 35, unit: 'days' },
grade: 'A'
}
]database
.collection('students')
.find({
'courseDuration.math': { $gt: 50 },
})
.toArray()
.then((res) => {
console.log(res)
client.close()
})
.catch((err) => {
console.log(err)
client.close()
})[
{
_id: new ObjectId("641fdf9eb3cd59e2c505f2a6"),
rollNo: 1,
firstName: 'Akshay',
lastName: 'Verma',
courseDuration: { math: 60, physics: 30, chemistry: 45, unit: 'days' },
grade: 'A'
},
{
_id: new ObjectId("641fdf9eb3cd59e2c505f2a7"),
rollNo: 2,
firstName: 'Sunil',
lastName: 'Singh',
courseDuration: { math: 75, physics: 60, chemistry: 45, unit: 'days' },
grade: 'C'
},
{
_id: new ObjectId("641fdf9eb3cd59e2c505f2af"),
rollNo: 10,
firstName: 'Akhilesh',
lastName: 'kumar',
courseDuration: { math: 75, physics: 40, chemistry: 35, unit: 'days' },
grade: 'A'
}
]sort() method to sort the selected documnets from MongoDB.students by firstName:database
.collection('students')
.find()
.sort({ firstName: 1 })
.toArray()
.then((res) => {
console.log(res)
client.close()
})
.catch((err) => {
console.log(err)
client.close()
})sort() method will return all documents from the students collection sorted in ascending order based on the firstName:[
{
_id: new ObjectId("641d46919bcf81fbf648c5a0"),
rollNo: '10',
firstName: 'Akhilesh',
lastName: 'kumar'
},
{
_id: new ObjectId("641d46919bcf81fbf648c597"),
rollNo: '1',
firstName: 'Akshay',
lastName: 'Verma'
},
{
_id: new ObjectId("641d46919bcf81fbf648c59d"),
rollNo: '7',
firstName: 'Arun',
lastName: 'Pratap'
},
{
_id: new ObjectId("641d46919bcf81fbf648c599"),
rollNo: '3',
firstName: 'Aruni',
lastName: 'Kumari'
},
{
_id: new ObjectId("641d46919bcf81fbf648c59c"),
rollNo: '6',
firstName: 'Maya',
lastName: 'Devi'
},
{
_id: new ObjectId("641d46919bcf81fbf648c59e"),
rollNo: '8',
firstName: 'Rahul',
lastName: 'Kumar'
},
{
_id: new ObjectId("641d46919bcf81fbf648c59a"),
rollNo: '4',
firstName: 'Sikka',
lastName: 'Singh'
},
{
_id: new ObjectId("641d46919bcf81fbf648c59b"),
rollNo: '5',
firstName: 'Sonu',
lastName: 'Kumar'
},
{
_id: new ObjectId("641d46919bcf81fbf648c59f"),
rollNo: '9',
firstName: 'Suhani',
lastName: 'Sah'
},
{
_id: new ObjectId("641d46919bcf81fbf648c598"),
rollNo: '2',
firstName: 'Sunil',
lastName: 'Singh'
}
]limit() method.limit() method accepts an integer value that specifies the maximum number of returned documents. For example:database
.collection('students')
.find()
.limit(3)
.toArray()
.then((res) => {
console.log(res)
client.close()
})
.catch((err) => {
console.log(err)
client.close()
})[
{
_id: new ObjectId("641d46919bcf81fbf648c597"),
rollNo: '1',
firstName: 'Akshay',
lastName: 'Verma'
},
{
_id: new ObjectId("641d46919bcf81fbf648c598"),
rollNo: '2',
firstName: 'Sunil',
lastName: 'Singh'
},
{
_id: new ObjectId("641d46919bcf81fbf648c599"),
rollNo: '3',
firstName: 'Aruni',
lastName: 'Kumari'
}
]skip() method.skip() method takes an integer that specifies the number of documents to skip. Here is an example:database
.collection('students')
.find()
.skip(5)
.toArray()
.then((res) => {
console.log(res)
client.close()
})
.catch((err) => {
console.log(err)
client.close()
})skip() method will skip the students from Roll no. 1 to Roll No. 5 from the students collection and return the rest of the documents of students collection.[
{
_id: new ObjectId("641d46919bcf81fbf648c59c"),
rollNo: '6',
firstName: 'Maya',
lastName: 'Devi'
},
{
_id: new ObjectId("641d46919bcf81fbf648c59d"),
rollNo: '7',
firstName: 'Arun',
lastName: 'Pratap'
},
{
_id: new ObjectId("641d46919bcf81fbf648c59e"),
rollNo: '8',
firstName: 'Rahul',
lastName: 'Kumar'
},
{
_id: new ObjectId("641d46919bcf81fbf648c59f"),
rollNo: '9',
firstName: 'Suhani',
lastName: 'Sah'
},
{
_id: new ObjectId("641d46919bcf81fbf648c5a0"),
rollNo: '10',
firstName: 'Akhilesh',
lastName: 'kumar'
}
]