Quedemy
Sign In
mongodb-querying-documents

MongoDB Querying Documents with Example


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.

Pre-requisites

  • Good Knowledge of Javascript, NodeJS and MongoDB Database
  • NodeJS and MongoDB must be installed on local machine. We can install mongoDB from mongodb.com

Introduction

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 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-querying
npm init -y
  • Create a file insertMany.js and insert students data to mongodb database
const { 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)
	})
  • Run node insertMany.js to insert student list into local mongodb database.

Querying All Documents from MongoDB

  • In general, we use find() method to fetch data from MongoDB database.
  • The find() method also accept an optional query object that helps to select certain documents from MongoDB database.
  • For example, we can fetch all the documents of the collection 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()
	})
  • The above code will return all documents from the collection 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'
  }
]

Querying Documents with Equality Condition

  • We can pass key/value pairs as optional query object to find() to select specific documents.
  • For example, we will pass the object { '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()
	})
  • In the above code block, the find() method will return the document where rollNo is equal to 3:
[
  {
    _id: new ObjectId("641d46919bcf81fbf648c599"),
    rollNo: '3',
    firstName: 'Aruni',
    lastName: 'Kumari'
  }
]

Querying Documents with Query Operators

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

Comparison operators allow you to compare a field to a specified value or another field. Here are some commonly used comparison operators:

  • $eq: Matches values that are equal to a specified value.
  • $ne: Matches values that are not equal to a specified value.
  • $gt: Matches values that are greater than a specified value.
  • $gte: Matches values that are greater than or equal to a specified value.
  • $lt: Matches values that are less than a specified value.
  • $lte: Matches values that are less than or equal to a specified value.
  • Here is an example of using the $eq operator:

Logical 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'
  }
]
  • $or
database
	.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'
  }
]
  • Combined $and and $or

Querying Nested Document by Matching an Object

database
	.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'
  }
]

Querying document using Nested Field

We can query documents using nested field and dot notation (i.e. field.nestedField)

Matching with Nested Field

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'
  }
]

Matching Nested Field Using Query Operator

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'
  }
]

Querying Documents in a Specific Order

  • We can use the sort() method to sort the selected documnets from MongoDB.
  • For example, we can sort all documents of collection 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()
	})
  • In the above code, the 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'
  }
]

Limiting Querying Documents

  • We can limit the number of documents returned by a query using the limit() method.
  • The 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()
	})
  • This will return the first 10 documents from the specified collection.
[
  {
    _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'
  }
]

Skipping Querying Documents

  • We can skip a certain number of documents from the beginning of the selected results using the skip() method.
  • The 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()
	})
  • In the above code block, The 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'
  }
]