Sign In
Sign In

How to Work with MongoDB Queries

How to Work with MongoDB Queries
Hostman Team
Technical writer
MongoDB
02.11.2024
Reading time: 10 min

MongoDB is not a traditional relational database management system. This is reflected in many aspects: the principles of database design, the format of stored data, the approach to scaling, and the query language.

The primary language for creating queries in relational databases is SQL. However, MongoDB uses its own syntax for queries. In this guide, we’ll discuss how to create queries and which commands are used.

Structure of MongoDB

A MongoDB database consists of collections similar to tables in relational databases. Each collection has its own unique name. Unlike table-based databases, collections do not have a strict data structure with a fixed number of columns and data types.

Collections store documents, which are objects that resemble JSON format. An example of an employee document might look like this:

{
  "name": "Mary",
  "surname": "Jameson",
  "age": 27,
  "salary": "100000",
  "department": "marketing",
  "date of birth": "15.02.1997"
}

Data in documents can be represented in various data types. In this example, all the data is described as strings.

Database and Collection-Level Queries

We will be writing and composing queries in MongoDB Compass. For more details on installing MongoDB on Ubuntu, refer to our tutorial. After installation, three databases will be available on the local server:

Image8

To display them, we use the show databases command:

show databases

# Output: admin 40.00 KiB config 60.00 KiB local 40.00 KiB

A shorter version, show dbs, can also be used:

show dbs

# Output: admin 40.00 KiB config 60.00 KiB local 40.00 KiB

To work with a specific database, use the use command:

use testdb

Output:

'switched to db testdb'

The testdb database does not exist on our server. If the terminal cannot find the specified database when executing the use command, it will create a new one with that name.

Use the db.createCollection("collection_name") command to create collections. Let’s create a collection in the testdb database:

db.createCollection('cloud')
{ ok: 1 }

To list collections:

show collections
cloud

To delete a collection, use the drop() command:

db.cloud.drop()
true

List collections again to confirm deletion:

show collections

To delete the entire database while working with it, use the db.dropDatabase() command:

db.dropDatabase()

Output:

{ ok: 1, dropped: 'testdb' }

Adding and Deleting Documents

Let’s restore the database and create a collection in it:

use testdb

# Output:
'switched to db testdb'
db.createCollection('employees')

# Output:
{ ok: 1 }

Then, we’ll add the first document:

db.employees.insert({
      name: "Mary",
      surname: "Jameson",
      age: 27,
      salary: 100000,
      department: "marketing",
      date_of_birth: "15.02.1997"
})

Output:

'DeprecationWarning: Collection.insert() is deprecated. Use insertOne, insertMany, or bulkWrite.'
{ acknowledged: true,
 insertedIds: { '0': ObjectId("637c9cbd7025c2523a76fe64") } }

After executing insert, the terminal suggests using the insertOne, insertMany, or bulkWrite methods to optimize queries, as insert is now deprecated.

insertOne - Adding a Single Document

The insertOne method adds one document to the collection:

db.employees.insertOne({
      name: "James",
      surname: "Johns",
      age: 37,
      salary: 150000,
      department: "QA",
      date_of_birth: "12.06.1987"
})

Output:

{ acknowledged: true,
 insertedId: ObjectId("637ca6127025c2523a76fe65") }

insertMany - Adding Multiple Documents

The insertMany method adds an array of documents to the collection:

db.employees.insertMany(
[{
      name: "Andrew",
      surname: "Stuart",
      age: 21,
      salary: 12000,
      department: "Tech Support",
      date_of_birth: "15.10.2003"
},
{
      name: "Natalie",
      surname: "Richardson",
      age: 45,
      salary: 200000,
      department: "HR",
      date_of_birth: "6.05.1979"
}]
)

Output:

{ acknowledged: true,
  insertedIds: {
    '0': ObjectId("637ca7817025c2523a76fe66"),
    '1': ObjectId("637ca7817025c2523a76fe67")
  }
}

bulkWrite - Performing Multiple Operations

The bulkWrite method allows you to perform multiple operations, including inserting, deleting, and updating documents:

db.employees.bulkWrite([{
      insertOne: {
          document: {
              name: "Michael",
              surname: "Smith",
              age: 32,
              salary: 20000,
              department: "Tech Support",
              date_of_birth: "10.01.1992"
          }
      }
}])

Output:

{ acknowledged: true,
  insertedCount: 1,
  insertedIds: { '0': ObjectId("637cafaa7025c2523a76fe68") },
  matchedCount: 0,
  modifiedCount: 0,
  deletedCount: 0,
  upsertedCount: 0,
  upsertedIds: {} }

Using these methods—insertOne, insertMany, and bulkWrite—can improve efficiency and provide more control over document management in MongoDB.

Document Search

The find() query is MongoDB's equivalent of SQL's SELECT. This query searches and displays documents in a collection. To start, let’s output all documents in the employees collection:

db.employees.find()

Output:

[
  {
    "_id": ObjectId("637c9cbd7025c2523a76fe64"),
    "name": "Mary",
    "surname": "Jameson",
    "age": 27,
    "salary": 100000,
    "department": "marketing",
    "date_of_birth": "15.02.1997"
  },
  {
    "_id": ObjectId("637ca6127025c2523a76fe65"),
    "name": "James",
    "surname": "Johns",
    "age": 37,
    "salary": 150000,
    "department": "QA",
    "date_of_birth": "12.06.1987"
  },
  {
    "_id": ObjectId("637ca7817025c2523a76fe66"),
    "name": "Andrew",
    "surname": "Stuart",
    "age": 21,
    "salary": 12000,
    "department": "Tech Support",
    "date_of_birth": "15.10.2003"
  },
  {
    "_id": ObjectId("637ca7817025c2523a76fe67"),
    "name": "Natalie",
    "surname": "Richardson",
    "age": 45,
    "salary": 200000,
    "department": "HR",
    "date_of_birth": "6.05.1979"
  }
]

Search by Criteria

To find a document with specific parameters, pass them as arguments to the find() query. For example, let’s find an employee with a salary of 50000:

db.employees.find({ salary: 50000 })

Output:

[]

In this case, no employees have a salary of 50000, so the output is empty.

If there are multiple parameters, list them separated by commas:

db.employees.find({ salary: 12000, name: "Andrew" })

Output:

[
  {
    "_id": ObjectId("637ca7817025c2523a76fe66"),
    "name": "Andrew",
    "surname": "Stuart",
    "age": 21,
    "salary": 12000,
    "department": "Tech Support",
    "date_of_birth": "15.10.2003"
  }
]

Find with OR Condition

To set an OR condition in the MongoDB query, use $or:

db.employees.find({ $or: [{ salary: 50000 }, { name: "Natalie" }] })

Output:

[
  {
    "_id": ObjectId("637ca7817025c2523a76fe67"),
    "name": "Natalie",
    "surname": "Richardson",
    "age": 45,
    "salary": 200000,
    "department": "HR",
    "date_of_birth": "6.05.1979"
  }
]

Search with Comparison

The following comparison operators are used:

  • $lt — less than

  • $lte — less than or equal to

  • $gt — greater than

  • $gte — greater than or equal to

  • $ne — not equal

For example, let’s find employees with a salary greater than 100000 and under the age of 30:

db.employees.find({ salary: { $gte: 100000 }, age: { $lt: 30 } })

Output:

[
  {
    "_id": ObjectId("637c9cbd7025c2523a76fe64"),
    "name": "Mary",
    "surname": "Jameson",
    "age": 27,
    "salary": 100000,
    "department": "marketing",
    "date_of_birth": "15.02.1997"
  }
]

Sorting

The sort() method sorts documents based on a given parameter and takes a number: 1 for ascending order or -1 for descending order. Let’s sort employees by age:

db.employees.find().sort({ age: 1 })

Output:

[
  {
    "_id": ObjectId("637ca7817025c2523a76fe66"),
    "name": "Andrew",
    "surname": "Stuart",
    "age": 21,
    "salary": 12000,
    "department": "Tech Support",
    "date_of_birth": "15.10.2003"
  },
  {
    "_id": ObjectId("637c9cbd7025c2523a76fe64"),
    "name": "Mary",
    "surname": "Jameson",
    "age": 27,
    "salary": 100000,
    "department": "marketing",
    "date_of_birth": "15.02.1997"
  },
  {
    "_id": ObjectId("637ca6127025c2523a76fe65"),
    "name": "James",
    "surname": "Johns",
    "age": 37,
    "salary": 150000,
    "department": "QA",
    "date_of_birth": "12.06.1987"
  },
  {
    "_id": ObjectId("637ca7817025c2523a76fe67"),
    "name": "Natalie",
    "surname": "Richardson",
    "age": 45,
    "salary": 200000,
    "department": "HR",
    "date_of_birth": "6.05.1979"
  }
]

Limiting Results

To limit the number of documents returned, use the limit() method:

db.employees.find().sort({ age: 1 }).limit(2)

Output:

[
  {
    "_id": ObjectId("637ca7817025c2523a76fe66"),
    "name": "Andrew",
    "surname": "Stuart",
    "age": 21,
    "salary": 12000,
    "department": "Tech Support",
    "date_of_birth": "15.10.2003"
  },
  {
    "_id": ObjectId("637c9cbd7025c2523a76fe64"),
    "name": "Mary",
    "surname": "Jameson",
    "age": 27,
    "salary": 100000,
    "department": "marketing",
    "date_of_birth": "15.02.1997"
  }
]

Document Updates

To update documents in a MongoDB database, use a query with the update() command. It takes two parameters: the first specifies which documents to update, and the second indicates which fields to change and their new values. Here’s an example:

db.employees.update({ name: 'Mary' },
{
  $set: {
    name: 'Anna',
    age: 51,
    date_of_birth: '15.11.1972'
  }
})

Then, to verify the update, we can search for documents with the new name:

db.employees.find({ name: 'Anna' })

Output:

[
  {
    "_id": ObjectId("637c9cbd7025c2523a76fe64"),
    "name": "Anna",
    "surname": "Jameson",
    "age": 51,
    "salary": 100000,
    "department": "marketing",
    "date_of_birth": "15.11.1972"
  }
]

Renaming Fields

To rename fields, use the $rename operator. In this case, let’s rename name to first_name:

db.employees.updateMany({}, {
  $rename: {
    name: 'first_name'
  }
})

Now, all documents with the name field will have it replaced by first_name.

Document Deletion

MongoDB provides two functions for deleting documents: deleteOne() and deleteMany().

deleteOne()

The deleteOne() function deletes the first document that matches the criteria. For example, let’s delete an employee named "Natalie":

db.employees.deleteOne({ first_name: 'Natalie' })

Output:

{ acknowledged: true, deletedCount: 1 }

deleteMany()

The deleteMany() function deletes all documents that match the criteria. Let’s delete all employees in the Tech Support department:

db.employees.deleteMany({ department: 'Tech Support' })

Output:

{ acknowledged: true, deletedCount: 2 }

After these deletions, only two documents should remain in the employees collection. Let’s check:

db.employees.find()

Final Output:

[
  {
    "_id": ObjectId("637c9cbd7025c2523a76fe64"),
    "first_name": "Anna",
    "surname": "Jameson",
    "age": 51,
    "salary": 100000,
    "department": "marketing",
    "date_of_birth": "15.11.1972"
  },
  {
    "_id": ObjectId("637ca6127025c2523a76fe65"),
    "first_name": "James",
    "surname": "Johns",
    "age": 37,
    "salary": 150000,
    "department": "QA",
    "date_of_birth": "12.06.1987"
  }
]

In summary, these operations—update, $rename, deleteOne, and deleteMany—allow you to manage document updates and deletions efficiently in MongoDB.

MongoDB Query Optimization

To improve the speed of your queries, consider the following tips:

  • Create indexes for frequently used queries.

  • Limit the number of returned documents. MongoDB retrieves all matching documents by default, so use the limit() method if you only need part of the result.

  • Return only necessary fields from documents. You can enhance query performance by specifying only the required fields in the search result.

  • Use more "selective" queries. For example, checking by _id will return no more than one document. Aim to use parameters in MongoDB queries that most accurately describe the documents you need.

Conclusion

MongoDB provides a straightforward query syntax that enables efficient document management within databases. In this material, we covered basic MongoDB queries that encompass primary document management tasks.

We used a database hosted locally, but you can also host a database in the cloud using Hostman Managed Databases. Cloud databases are easier to administer and scale and can be managed and created using a web interface.

MongoDB
02.11.2024
Reading time: 10 min

Similar

Node.js

How to Connect a Node.js App to MongoDB

When developing Node.js applications, you might need to store data somewhere. Using application variables or files on the host machine as data storage is not always convenient. A better option to consider is connecting to an external database application. MongoDB is great for integration with Node.js. In MongoDB, data is presented in JSON format, which works well with JavaScript.  In this article, we'll show you how to connect a MongoDB database to your Node.js application and look at several common database queries. This guide works for Node.js version 14 and higher and MongoDB version 4.4 and higher. Test database As a test database, we will use the testdb database, which contains the employees collection. It stores information about a company's employees: their department, date of birth, salary level, and other information.  We will connect the Node.js application to this database, and we will work with the employees collection. Creating a User in MongoDB Compass Create a new user to work with the database. For testing purposes, we will assign the user administrator privileges for all databases; however, you shouldn't do this in production—it will negatively impact security. Open a MongoDB Shell terminal and run the following query: >use admin > db.createUser({ user: "Hostman", pwd: "password", roles: [ { role: "userAdmin", db: "admin" }, { role: "dbAdminAnyDatabase", db: "admin" } ] }) Output: {ok: 1} We have created a user named "Hostman" with a password "password" and will use it to connect to the database. Setup To connect a Node.js application to a MongoDB database, you need to install the additional mongodb package: npm install mongodb --savenpm install mongodb-core --save Connection The main object through which we will interact with the MongoDB database is an object of the MongoClient class. Let's import this class: const {MongoClient} = require('mongodb') And declare the DBclient object using the constructor: const MongoDBclient = new MongoClient('URI') The class constructor is given a URI as input, which contains information about the user, IP, and server port. Here's the URI structure: mongodb://login:password@IP:PORT/?authMechanism=method In the case of a database hosted on a local machine, the URI looks like this: mongodb://Hostman:[email protected]:27017/?authMechanism=DEFAULT Here, we are using: Hostman as username; password as password; port 27017; DEFAULT as the authorization mechanism. Let's connect to the server with the database: const {MongoClient} = require('mongodb') const MongoDBclient = new MongoClient('mongodb://Hostman:[email protected]:27017/?authMechanism=DEFAULT') const connect = async() =>{ try { await MongoDBclient.connect() console.log("Successfully connected to database") await MongoDBclient.close() console.log("Connection closed") } catch (e) { console.log(e) } } connect() Output: Successfully connected to databaseConnection closed Any interactions with the database are asynchronous operations, therefore, it is necessary to use async and await. Let's look at several popular operations. Inserting documents To insert a new document, you need to execute a query to the database with document data as an argument. Inserting a single document const {MongoClient} = require('mongodb') const MongoDBclient = new MongoClient('mongodb://Hostman:[email protected]:27017/?authMechanism=DEFAULT') const employee = { surname: 'Smith', age: 45, salary: 260000, department: 'DevRel', date_of_birth: '15/11/1977', first_name: 'John' } const Insert = async() =>{ try { await MongoDBclient.connect() console.log("Successfully connected to database") const employees = MongoDBclient.db('testdb').collection('employees') await employees.insertOne(employee) await MongoDBclient.close() console.log("Connection closed") } catch (e) { console.log(e) } } Insert() Inserting multiple documents const {MongoClient} = require('mongodb') const MongoDBclient = new MongoClient('mongodb://Hostman:[email protected]:27017/?authMechanism=DEFAULT') const ManyEmployees = [{ surname: 'Hernandez', age: 27, salary: 160000, department: 'Legal Department', date_of_birth: '15/05/1995', first_name: 'Juan' }, { surname: 'Miles', age: 30, salary: 200000, department: 'Tech Support', date_of_birth: '06/02/1992', first_name: 'Mary' }] const Insert = async() =>{ try { await MongoDBclient.connect() console.log("Successfully connected to database") const employees = MongoDBclient.db('testdb').collection('employees') await employees.insertMany(ManyEmployees) await MongoDBclient.close() console.log("Connection closed") } catch (e) { console.log(e) } } Insert() Let's check the total number of documents in the collection after insertions: const {MongoClient} = require('mongodb') const MongoDBclient = new MongoClient('mongodb://Hostman:[email protected]:27017/?authMechanism=DEFAULT') const Count = async() =>{ try { await MongoDBclient.connect() console.log("Successfully connected to database") const AllDocuments = await MongoDBclient.db('testdb').collection('employees').find().toArray() console.log("Number of documents in the database:", AllDocuments.length) await MongoDBclient.close() console.log("Connection closed") } catch (e) { console.log(e) } } Count() Output: Successfully connected to databaseNumber of documents in the database: 5Connection closed Querying documents To query documents in the database, use the following construction: MongoClienObject.db('dbname').collection('collectionname').operation Where: MongoClienObject is an object of the MongoClient class; dbname is the name of the database we are accessing; collectionname is the name of the collection we are accessing; operation is the query to a database or collection, for example, findOne; If the request is made directly to the database, then collection('collectionname') is not needed. Let's display all documents in the employees collection: const {MongoClient} = require('mongodb') const MongoDBclient = new MongoClient('mongodb://Hostman:[email protected]:27017/?authMechanism=DEFAULT') const Find = async() =>{ try { await MongoDBclient.connect() console.log("Successfully connected to database") const AllDocuments = await MongoDBclient.db('testdb').collection('employees').find().toArray() console.log(AllDocuments) await MongoDBclient.close() console.log("Connection closed") } catch (e) { console.log(e) } } Find() Ouput: Connection successful [ { _id: new ObjectId("637c9cbd7025c2523a76fe64"), surname: 'Williams', age: 50, salary: 100000, department: 'marketing', date_of_birth: '15/11/1972', first_name: 'Natalie' }, { _id: new ObjectId("637ca6127025c2523a76fe65"), surname: 'Rubio', age: 35, salary: 200000, department: 'QA', date_of_birth: '12/06/1987', first_name: 'Manuel' } ] Connection closed Updating documents Updating documents is performed in the same way as the operations above. Updating a single document const {MongoClient} = require('mongodb') const MongoDBclient = new MongoClient('mongodb://Hostman:[email protected]:27017/?authMechanism=DEFAULT') const Update = async() =>{ try { await MongoDBclient.connect() console.log("Successfully connected to database") const employees = MongoDBclient.db('testdb').collection('employees') await employees.findOneAndUpdate({first_name: 'John'} , { $set: {first_name: "Johnny"}}) await MongoDBclient.close() console.log("Connection closed") } catch (e) { console.log(e) } } Update() Updating multiple documents const {MongoClient} = require('mongodb') const MongoDBclient = new MongoClient('mongodb://Hostman:[email protected]:27017/?authMechanism=DEFAULT') const Update = async() =>{ try { await MongoDBclient.connect() console.log("Successfully connected to database") const employees = MongoDBclient.db('testdb').collection('employees') await employees.updateMany({$or:[{department: 'DevRel'},{department: 'marketing'}]} , { $set: {department: "PR"}}) await MongoDBclient.close() console.log("Connection closed") } catch (e) { console.log(e) } } Update() Conclusion MongoDB is a great tool, especially when coupled with Node.js. In this material, we used a local database, but there are other options, like cloud. At Hostman, you can deploy a MongoDB cloud database in a few seconds and start working in no time.
21 May 2024 · 7 min to read
MongoDB

How to Install MongoDB on Ubuntu 22.04: Step-by-Step Guide

MongoDB is a leading NoSQL database system renowned for its performance, scalability, and flexibility. This guide walks you through the installation process of MongoDB on Ubuntu 22.04, enabling you to harness its robust capabilities for your projects. If you're looking to set up MongoDB on your Ubuntu system, having a basic grasp of essential Linux terminal commands and familiarity with Ubuntu as your OS is key. Ensure that you're using a 64-bit architecture OS since MongoDB installation is tailored for this platform. Prerequisites Before proceeding, ensure you have: A cloud server running Ubuntu 22.04. A root user or a user with sudo privileges. Access to the server via SSH. Step 1: Preparing the Ubuntu System and Authorizing via SSH Connect to your cloud server via SSH: ssh username@your_server_ip Replace username with your actual username and your_server_ip with your server's IP address. You'll be prompted to enter your user's password. Once logged in, update the package index and upgrade installed packages with the commands: sudo apt update && sudo apt upgrade -y Step 2: Adding MongoDB Repository Import the MongoDB GPG key for package verification. To import the MongoDB GPG open key for version 6.0, begin by opening your terminal. Next, input the command below to fetch and add the key: wget -qO - https://www.mongodb.org/static/pgp/server-7.0.asc | sudo apt-key add - Executing this command will return an 'OK' status, confirming that the key has been added to the MongoDB instance. You will also see a warning that apt-key is deprecated, however, the installation process will still work. Once you've done so, the key import process should proceed smoothly. However, if your system doesn't have GNU Privacy Guard (gnupg) installed, you may encounter an error. To resolve this, use the following terminal command to install the program: sudo apt install -y gnupg2 Then run the import command again. It should be successful. To verify that the key has been added successfully, you can run the command: apt-key list Executing this command will display a list of keys, and you should find the MongoDB key among them in the output. Add the MongoDB repository to your system: You’re at a point where your APT setup isn’t yet aware of where to locate the mongodb-org package for installing MongoDB's latest version. APT, when fetching and installing packages, scans two specific locations on your server for online sources: the sources.list file and the sources.list.d directory. The sources.list file itemizes active APT data sources, each on a separate line, prioritizing the most preferred ones. Meanwhile, the sources.list.d directory is where you can incorporate additional sources as separate files. Execute this command to generate a new file named mongodb-org-7.0.list within the sources.list.d directory. echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list Update the package index once more. Now that you’ve executed the command, proceed by refreshing your server’s local package index. This step is crucial for ensuring APT can locate the mongodb-org package:   sudo apt-get update Managed solution for Backend development Step 3: Installing MongoDB With the package index updated, you’re ready to install MongoDB: Install MongoDB using the command: sudo apt-get install -y mongodb-org When prompted, press Y and then ENTER to confirm your intention to install the package. Once the installation process is complete, MongoDB will be successfully installed on your system. However, it’s not yet operational. Your next step involves starting MongoDB and verifying its functionality. Start the MongoDB service and enable it to start automatically on boot. You'll need to manually start the MongoDB service using the systemctl command. Here's the command you should run:   sudo systemctl start mongod Once you’ve verified that the MongoDB service is running as expected, you should enable it to start automatically at boot. Here’s the command to achieve that: sudo systemctl enable mongod Executing this command will configure the MongoDB service to start up automatically every time the system boots up or is restarted. Step 4: Verifying MongoDB Installation Check the MongoDB service status to ensure it's running. To check the status of the MongoDB service, you can use the systemctl command without specifying the .service suffix. Here's how you do it: sudo systemctl status mongod This command will return an output similar to the following, confirming that the MongoDB service is operational and running smoothly: An active (running) status indicates MongoDB is functioning properly. Step 5: Managing MongoDB Service To stop MongoDB, use the command: sudo systemctl stop mongod To restart MongoDB, use the command: sudo systemctl restart mongod To disable MongoDB, use the command: sudo systemctl disable mongod Conclusion Congratulations on successfully completing the MongoDB installation on Ubuntu 22.04! You've taken a significant step towards leveraging MongoDB's capabilities to efficiently store, manage, and retrieve your data. MongoDB's flexible and scalable nature makes it an ideal choice for a wide range of applications, from small-scale projects to enterprise-level solutions. Furthermore, remember to prioritize security by following best practices and regularly updating your MongoDB instance. Securing your database environment helps safeguard sensitive data and ensures compliance with industry regulations.
17 May 2024 · 5 min to read

Do you have questions,
comments, or concerns?

Our professionals are available to assist you at any moment,
whether you need help or are just unsure of where to start.
Email us
Hostman's Support