Reader small image

You're reading from  Mastering MongoDB 7.0 - Fourth Edition

Product typeBook
Published inJan 2024
PublisherPackt
ISBN-139781835460474
Edition4th Edition
Concepts
Right arrow
Authors (7):
Marko Aleksendrić
Marko Aleksendrić
author image
Marko Aleksendrić

Marko Aleksendrić is an analyst, an ex-scientist, and a freelance self-taught web developer with over 20 years of experience. Marko has authored the book Modern Web Development with the FARM Stack, published by Packt Publishing. With a keen interest in backend and frontend development, he has been an avid MongoDB user for the last 15 years for various web and data analytics-related projects, with Python and JavaScript as his main tools.
Read more about Marko Aleksendrić

Arek Borucki
Arek Borucki
author image
Arek Borucki

Arek Borucki, a recognized MongoDB Champion and certified database administrator, has been working with MongoDB technology since 2016. As principal SRE database engineer, he works closely with technologies such as MongoDB, Elasticsearch, PostgreSQL, Kafka, Kubernetes, Terraform, AWS, and GCP. His extensive experience includes working with renowned companies such as Amadeus, Deutsche Bank, IBM, Nokia, and Beamery. Arek is also a Certified Kubernetes Administrator and developer, an active speaker at international conferences, and a co-author of questions for the MongoDB Associate DBA Exam.
Read more about Arek Borucki

Leandro Domingues
Leandro Domingues
author image
Leandro Domingues

Leandro Domingues is a MongoDB Community Champion and a Microsoft Data Platform MVP alumnus. Specializing in NoSQL databases, focusing on MongoDB, he has authored several articles and is also a speaker and organizer of events and conferences. In addition to teaching MongoDB, he was a professor at one of the largest universities in Brazil. Leandro is passionate about MongoDB and is a mentor and an inspiration to many developers and administrators. His efforts make MongoDB a more comprehensible tool for everyone.
Read more about Leandro Domingues

Malak Abu Hammad
Malak Abu Hammad
author image
Malak Abu Hammad

Malak Abu Hammad is a seasoned software engineering manager at Chain Reaction, with a decade of expertise in MongoDB. She has carved a niche for herself not only in MongoDB but also in essential web app technologies. Along with conducting various online and offline workshops, Malak is a MongoDB Champion and a founding member of the MongoDB Arabic Community. Her vision for MongoDB is a future with an emphasis on Arabic localization, aimed at bridging the gap between technology and regional dialects.
Read more about Malak Abu Hammad

Elie Hannouch
Elie Hannouch
author image
Elie Hannouch

Elie Hannouch is a senior software engineer and digital transformation expert. A driving force in the tech industry, he has a proven track record of delivering robust, scalable, and impactful solutions. As a start-up founder, Elie combines his extensive engineering background with strategic innovation to redefine how enterprises operate in today's digital age. Apart from being a MongoDB Champion, Elie leads the MongoDB, Google, and CNCF communities in Lebanon and works toward empowering aspiring tech professionals by demystifying complex concepts and inspiring a new generation of tech enthusiasts.
Read more about Elie Hannouch

Rajesh Nair
Rajesh Nair
author image
Rajesh Nair

Rajesh Nair is a software professional from Kerala, India, with over 12 years of experience working in various MNCs. He started his career as a database administrator for multiple RDBMS technologies, including Progress OpenEdge and MySQL. Rajesh also managed huge datasets for critical applications running on MongoDB as a MongoDB administrator for several years. He has worked on technologies such as MongoDB, AWS, Java, Kafka, MySQL, Progress OpenEdge, shell scripting, and Linux administration. Rajesh is currently based out of Amsterdam, Netherlands, working as a senior software engineer.
Read more about Rajesh Nair

Rachelle Palmer
Rachelle Palmer
author image
Rachelle Palmer

Rachelle Palmer is the Product Leader for Developer Database Experience and Developer Education at MongoDB, overseeing the driver client libraries, documentation, framework integrations, and MongoDB University. She has built sample applications for MongoDB in Java, PHP, Rust, Python, Node.js, and Ruby. Rachelle joined MongoDB in 2013 and was previously the director of the technical services engineering team, creating and managing the team that provided support and CloudOps to MongoDB Atlas.
Read more about Rachelle Palmer

View More author details
Right arrow

CRUD Operations and Basic Queries

In this chapter, you will learn how to use the MongoDB Shell for database administration. Starting with simple create, read, update, and delete (CRUD) operations using Ruby and Python drivers, you will master scripting and get a broader perspective on how to interact with MongoDB across different programming environments. You will learn what the MongoDB Stable API (previously labeled the Versioned API) means for developers, and the features it provides. Finally, you will explore authentication and authorization using the MongoDB Community Edition and its paid counterpart, the Enterprise Edition.

This chapter will cover the following topics:

  • Understanding MongoDB CRUD operations
  • Performing CRUD operations using Ruby and Python drivers
  • Executing batch operations using mongosh
  • Administering and implementing authentication with MongoDB

Technical requirements

To follow along with the code in this chapter, you will need to install MongoDB locally or connect to a MongoDB Atlas database. You can download the MongoDB Community Edition from mongodb.com or use the fully managed database-as-a-service (DBaaS) MongoDB Atlas offering, which provides a free tier as well as seamless upgrades to the latest version.

Most examples are compatible with the new mongosh shell, but you may want to use the legacy shell, mongo, or enable mongosh backwards compatibility using mongosh snippets.

You will also need to download the official drivers for the language of your choice—Ruby or Python: https://www.mongodb.com/docs/drivers/.

To follow along with the code in this chapter, you will need the following:

  • mongosh shell
  • Connection with the MongoDB Atlas database
  • Official drivers for the language of your choice—Ruby or Python

MongoDB CRUD operations

Regardless of why you are using a MongoDB server, you'll need to perform CRUD operations on it. These fundamental methods, collectively known as CRUD operations, form the basis of interacting with a MongoDB server. To modify MongoDB documents, the process involves connecting to the server, querying the relevant documents, adjusting the specified properties, and subsequently transmitting the data back to the database for updates. Each CRUD operation serves a distinct purpose:

  • The create operation is used to insert new documents in the MongoDB database
  • The read operation is used to query a document in the database
  • The update operation is used to modify existing documents in the database
  • The delete operation is used to remove documents in the database

CRUD using mongosh

mongosh is equivalent to the administration console used by relational databases.

  1. To connect to mongosh, enter the following command:
    mongosh "mongodb...

CRUD using the Ruby driver

The Ruby driver was originally maintained by an external community member who was later hired by MongoDB. Subsequently, Ruby became one of the first languages to receive official support from MongoDB with an official driver.

MongoDB Ruby driver includes an integrated query cache. Once activated, this cache retains outcomes from previous find and aggregation operations. When those queries are executed again, the driver serves the cached results, eliminating redundant database interactions. An example of using the query cache can be found later in this chapter, in the Mongoid ODM section.

The recommended method for connecting to a MongoDB instance with Ruby is through the official MongoDB Ruby driver on GitHub.

Connecting to a database

Add mongo to your Gemfile, as follows:

gem "mongo"

To install the driver manually, execute the following command:

gem install mongo

Then, in your class, you can connect to a database, as shown...

CRUD using the Python driver

Python is a powerful programming language that provides robust web development capabilities, when paired with frameworks such as FastAPI. For MongoDB integration with Python, you can use MongoEngine as well as the official MongoDB low-level driver, PyMongo. PyMongo can be easily installed using pip:

$ python -m pip install pymongo

You can use the following connection snippet to test the connection to your MongoDB deployment:

from pymongo import MongoClient
# Replace the placeholder with your connection string
uri = "<connection string>"
# Create a new client and connect to the server
client = MongoClient(uri)
# Send a ping to confirm a successful connection
try:
    client.admin.command('ping')
    print("Pinged your deployment. You successfully connected to MongoDB!")
except Exception as e:
    print(e)

PyMongo is MongoDB's officially supported...

Regular expressions

There are several considerations that you have to take into account when querying in MongoDB. Let's look at some best practices for using regular expressions, query results, cursors, and deleting documents:

db.books.find({"name": /mongo/})

This is done to search for books in your books collection that contain the mongo name. It is the equivalent of an SQL LIKE query.

Note

MongoDB uses Perl Compatible Regular Expression (PCRE) version 8.42 with UTF-8 support.

While querying, you can use the following options:

Administration

Integration with MongoDB offers a seamless experience due to its non-relational, schema-free design. Without the constraints of schema migrations, you can streamline your database operations, thus minimizing database administrative overhead.

However, for optimal speed and performance in MongoDB, there are various tasks that experienced MongoDB developers or architects can perform. Management typically spans four distinct levels, each with increasing granularity: process, database, collection, and index.

At the process level, there is the shutDown command to shut down the MongoDB server.

At the database level, you have the following commands:

  • dropDatabase: To drop the entire database
  • listCollections: To retrieve the collection names in the current database

In comparison, at the collection level, the following commands are used:

  • drop: To drop a collection
  • create: To create a collection
  • renameCollection: To rename a collection...

Secure access to MongoDB

As the volume and sensitivity of data stored in databases grows, the importance of robust security measures becomes paramount. MongoDB recognizes this and has designed a suite of security tools and protocols to ensure that your data remains protected against unauthorized access and potential breaches. It provides various features, such as authentication, access control, and encryption, to secure your MongoDB deployments. It's crucial to understand the overarching principles that guide MongoDB's approach to database security.

Authentication and authorization

Authentication and authorization are closely connected. Authentication is the process of verifying the identity of a client. When access control (authorization) is enabled, MongoDB requires all clients to authenticate themselves in order to determine their access.

Authorization is about determining which actions a user can take on a resource. In the next sections, you'll explore authentication...

MongoDB Stable API

Introduced in MongoDB 5.0, the Stable API provides a guarantee that the API will not break for client-server communication. The Stable API is declared when using any driver or mongosh, in a similar fashion to the following mongosh example:

mongosh --apiVersion 1

Note

1 is the only API version available as of MongoDB 7.0.

StableAPI guarantees backward compatibility between MongoDB server upgrades. This means that you can continue upgrading your MongoDB server without any significant risk, i.e., your application connected to the MongoDB server will behave differently.

This guarantee holds correct under the following three constraints:

  • You need to declare apiVersion in the client
  • You need to use a supported version of the official MongoDB client
  • You can only use commands and features that are supported in this API version

Following the third constraint, as of apiVersion='1', you can use any of the following commands:

...

Summary

This chapter explored the basics of CRUD operations. Starting from mongosh, you learned how to insert, delete, read, and modify documents, and learned the difference between one-off inserts and inserting data in batches for performance. Additionally, the chapter discussed administration tasks and how to perform them in mongosh. Finally, the chapter briefly covered security and authentication with MongoDB, the new versioning scheme, and the new shell, mongosh.

The next chapter will explore MongoDB schema design principles and techniques for effective data representation—essential for optimizing performance and scalability.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Mastering MongoDB 7.0 - Fourth Edition
Published in: Jan 2024Publisher: PacktISBN-13: 9781835460474
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (7)

author image
Marko Aleksendrić

Marko Aleksendrić is an analyst, an ex-scientist, and a freelance self-taught web developer with over 20 years of experience. Marko has authored the book Modern Web Development with the FARM Stack, published by Packt Publishing. With a keen interest in backend and frontend development, he has been an avid MongoDB user for the last 15 years for various web and data analytics-related projects, with Python and JavaScript as his main tools.
Read more about Marko Aleksendrić

author image
Arek Borucki

Arek Borucki, a recognized MongoDB Champion and certified database administrator, has been working with MongoDB technology since 2016. As principal SRE database engineer, he works closely with technologies such as MongoDB, Elasticsearch, PostgreSQL, Kafka, Kubernetes, Terraform, AWS, and GCP. His extensive experience includes working with renowned companies such as Amadeus, Deutsche Bank, IBM, Nokia, and Beamery. Arek is also a Certified Kubernetes Administrator and developer, an active speaker at international conferences, and a co-author of questions for the MongoDB Associate DBA Exam.
Read more about Arek Borucki

author image
Leandro Domingues

Leandro Domingues is a MongoDB Community Champion and a Microsoft Data Platform MVP alumnus. Specializing in NoSQL databases, focusing on MongoDB, he has authored several articles and is also a speaker and organizer of events and conferences. In addition to teaching MongoDB, he was a professor at one of the largest universities in Brazil. Leandro is passionate about MongoDB and is a mentor and an inspiration to many developers and administrators. His efforts make MongoDB a more comprehensible tool for everyone.
Read more about Leandro Domingues

author image
Malak Abu Hammad

Malak Abu Hammad is a seasoned software engineering manager at Chain Reaction, with a decade of expertise in MongoDB. She has carved a niche for herself not only in MongoDB but also in essential web app technologies. Along with conducting various online and offline workshops, Malak is a MongoDB Champion and a founding member of the MongoDB Arabic Community. Her vision for MongoDB is a future with an emphasis on Arabic localization, aimed at bridging the gap between technology and regional dialects.
Read more about Malak Abu Hammad

author image
Elie Hannouch

Elie Hannouch is a senior software engineer and digital transformation expert. A driving force in the tech industry, he has a proven track record of delivering robust, scalable, and impactful solutions. As a start-up founder, Elie combines his extensive engineering background with strategic innovation to redefine how enterprises operate in today's digital age. Apart from being a MongoDB Champion, Elie leads the MongoDB, Google, and CNCF communities in Lebanon and works toward empowering aspiring tech professionals by demystifying complex concepts and inspiring a new generation of tech enthusiasts.
Read more about Elie Hannouch

author image
Rajesh Nair

Rajesh Nair is a software professional from Kerala, India, with over 12 years of experience working in various MNCs. He started his career as a database administrator for multiple RDBMS technologies, including Progress OpenEdge and MySQL. Rajesh also managed huge datasets for critical applications running on MongoDB as a MongoDB administrator for several years. He has worked on technologies such as MongoDB, AWS, Java, Kafka, MySQL, Progress OpenEdge, shell scripting, and Linux administration. Rajesh is currently based out of Amsterdam, Netherlands, working as a senior software engineer.
Read more about Rajesh Nair

author image
Rachelle Palmer

Rachelle Palmer is the Product Leader for Developer Database Experience and Developer Education at MongoDB, overseeing the driver client libraries, documentation, framework integrations, and MongoDB University. She has built sample applications for MongoDB in Java, PHP, Rust, Python, Node.js, and Ruby. Rachelle joined MongoDB in 2013 and was previously the director of the technical services engineering team, creating and managing the team that provided support and CloudOps to MongoDB Atlas.
Read more about Rachelle Palmer

Option

Description

i

This option queries case insensitivity.

m

This option only applies to multiline strings with anchors (* for the start and $ for the end). In this case, defining the m option will match the pattern at the beginning or end of each line...