MongoDB

Nehajoshi
Catalysts Reachout
Published in
7 min readNov 8, 2022

MongoDB is a document-oriented NoSQL database used for high volume data storage. Instead of using tables and rows as in the traditional relational databases, MongoDB makes use of collections and documents.

Features of MongoDB

  • MongoDB stores the main subject in the minimal number of documents and not by breaking it up into multiple relational structures like RDBMS.
  • MongoDB increases the data availability with multiple copies of data on different servers. By providing redundancy, it protects the database from hardware failures. If one server goes down, the data can be retrieved easily from other active servers which also had the data stored on them.
  • The rows (or documents as called in MongoDB) doesn’t need to have a schema defined beforehand. Instead, the fields can be created on the fly.
  • The data model available within MongoDB allows you to represent hierarchical relationships, to store arrays, and other more complex structures more easily.
  • The MongoDB environments are very scalable. Companies across the world have defined clusters with some of them running 100+ nodes with around millions of documents within the database.
  • Aggregation operations process data records and return the computed results. It is similar to the GROUPBY clause in SQL. A few aggregation expressions are sum, avg, min, max, etc.

Parts of MongoDB

  • Drivers: The drivers support by the MongoDB are C, C++, C#, and .Net, Go, Java, Node.js, Perl, PHP, Python, Motor, Ruby, Scala, Swift, Mongoid.
  • MongoDB Shell: MongoDB Shell or mongo shell is an interactive JavaScript interface for MongoDB used for queries, data updates, and also performs administrative operations.
  • Storage Engine: It is used to manage how data is stored in the memory and on the disk. MongoDB can have multiple search engines. The default search engine, known as Wired Tiger Storage Engine efficiently works with data like reading, writing, etc.

How MongoDB works?

1. Application layer: The application layer can also be called the final abstraction layer. It is made up of the front end and the back end. The front end or user interface is the platform where the user interacts with the database through a mobile app (Android or iOS) or directly from the web. On the other hand, the backend is the server, which performs logical operations and uses queries to interact with MongoDB with drivers.

2. Data layer: The data layer consists directly of the MongoDB server. When queries are sent from the backend of the application layer, MongoDB receives the queries and sends them on to the storage engine. This is what reads or writes the data in the memory.

MongoDB operators

What are MongoDB operators?

Operators are special symbols that help compilers perform mathematical or logical tasks. MongoDB offers several types of operators to interact with the database. There are 2types of operators: Query and projection operators and Update operators.

Types of Query and projection operators:

1] Logical Operators: Logical operators are often used to filter data based on the given conditions. They also allow for the evaluation of many conditions, which we’ll discuss in more detail.

  • $and: Joins query clauses with a logical AND returns all documents that match the conditions of both clauses.
  • $not: Inverts the effect of a query expression and returns documents that do not match the query expression.
  • $nor: Joins query clauses with a logical NOR returns all documents that fail to match both clauses.
  • $or: Joins query clauses with a logical OR returns all documents that match the conditions of either clause.

2] Comparison Operators: Comparison operators can be used to compare values in one or more documents.

  • $eq: Matches values that are 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.
  • $in: Matches any of the values specified in an array.
  • $lt: Matches values that are less than a specified value.
  • $lte: Matches values that are less than or equal to a specified value.
  • $ne: Matches all values that are not equal to a specified value.
  • $nin: Matches none of the values specified in an array.

3] Element Operators: The element query operators can identify documents using the fields of the document. Element operators consist of $exists and $type.

  • $exists: Matches documents that have the specified field.
  • $type: Selects documents if a field is of the specified type.

4] Array Operators

MongoDB also consists of array operators, to query documents containing arrays. There are three primary operators:$all ,$elemMatch and $size. We’ll discuss each one in detail below.

  • $all: Matches arrays that contain all elements specified in the query.
  • $elemMatch: Selects documents if element in the array field matches all the specified $elemMatch conditions.
  • $size: Selects documents if the array field is a specified size.

5] Geospatial Operators

MongoDB allows you to store geospatial data in the form of GeoJSON types. GeoJSON is an open-standard format based on the JavaScript object notation that can represent geographical features and support non-spatial attributes. There are two types of geospatial operators : query selectors and geometry specifiers.

a)Query selectors:

  • $geoIntersects:Selects geometries that intersect with a GeoJSON geometry. The 2dsphere index supports $geoIntersects.
  • $geoWithin:Selects geometries within a bounding GeoJSON geometry. The 2dsphere and 2d indexes support $geoWithin.
  • $near:Returns geospatial objects in proximity to a point. Requires a geospatial index. The 2dsphere and 2d indexes support $near.
  • $nearSphere: Returns geospatial objects in proximity to a point on a sphere. Requires a geospatial index. The 2dsphere and 2d indexes support $nearSphere.

b) Geometry specifiers:

  • $box: Specifies a rectangular box using legacy coordinate pairs for $geowithin queries. The 2d index supports $box
  • $center: Specifies a circle using legacy coordinate pairs to $geowithin queries when using planar geometry. The 2d index supports $center
  • $centerSphere:: Specifies a circle using either legacy coordinate pairs or GeoJSON format for $geowithin queries when using spherical geometry. The 2dsphere and 2d indexes support $centerSphere.
  • $geometry: Specifies a geometry in GeoJSON format to geospatial query operators.
  • $maxDistance: Specifies a maximum distance to limit the results of $near and $nearSpehere queries. The 2dsphere and 2d indexes support $maxDistance.
  • $mindistance: Specifies a minimum distance to limit the results of $near and $nearSphere queries. For use with 2dSphere index only.
  • $polygon: Specifies a polygon to using legacy coordinate pairs for $geowithin queries. The 2d index supports $center.

6] Projection Operators: Projection operators to mention the fields returned by an operation :

  • $: Projects the first element in an array that matches the query condition.
  • $elemMatch: Projects the first element in an array that matches the specified $elemMatch condition.
  • $meta: Projects the available per-document metadata.
  • $slice: Limits the number of elements projected from an array. Supports skip and limit slices.

7]Evaluation Operators: Evaluation operators are used to gauge the overall data structure or individual field inside a document.

  • $expr: Allows use of aggregation expressions within the query language.
  • $jsonSchema: Validate documents against the given JSON Schema.
  • $mod: Performs a modulo operation on the value of a field and selects documents with a specified result.
  • $regex: Selects documents where values match a specified regular expression.
  • $text: Performs text search.
  • $where: Matches documents that satisfy a JavaScript expression.

8] Bitwise Operators: Bitwise operators return data based on bit position conditions.

  • $bitsAllClear: Matches numeric or binary values in which a set of bit positions all have a value of 0.
  • $bitsAllSet: Matches numeric or binary values in which a set of bit positions all have a value of 1.
  • $bitsAnyClear: Matches numeric or binary values in which any bit from a set of bit positions has a value of 0.
  • $bitsAnySet: Matches numeric or binary values in which any bit from a set of bit positions has a value of 1.Bitwise operators return data based on bit position conditions.

9]Miscellaneous Query Operators:

  • $comment: Adds a comment to a query predicate.
  • $rand: Generates a random float between 0 and 1.
  • $natural: A special hint that can be provided via the sort()or hint()methods that can be used to force either a forward or reverse collection scan.

Types of Update operators:

1]Fields

  • $currentDate: Sets the value of a field to current date, either as a Date or a Timestamp.
  • $inc: Increments the value of the field by the specified amount.
  • $min: Only updates the field if the specified value is less than the existing field value.
  • $max: Only updates the field if the specified value is greater than the existing field value.
  • $mul: Multiplies the value of the field by the specified amount.
  • $rename: Renames a field.
  • $set: Sets the value of a field in a document.
  • $setOnInsert: Sets the value of a field if an update results in an insert of a document. Has no effect on update operations that modify existing documents.
  • $unset: Removes the specified field from a document.

2]Array

  • $: Acts as a placeholder to update the first element that matches the query condition.
  • $[]: Acts as a placeholder to update all elements in an array for the documents that match the query condition.
  • $[<identifier>]: Acts as a placeholder to update all elements that match the array filters condition for the documents that match the query condition.
  • $addToSet: Adds elements to an array only if they do not already exist in the set.
  • $pop: Removes the first or last item of an array.
  • $pull: Removes all array elements that match a specified query.
  • $push: Adds an item to an array.
  • $pullAll: Removes all matching values from an array.

3] Modifiers

  • $each:Modifies the $push and $addToSet operators to append multiple items for array updates.
  • $position: Modifies the $push operator to specify the position in the array to add elements.
  • $slice: Modifies the $push operator to limit the size of updated arrays.
  • $sort: Modifies the $push operator to reorder documents stored in an array.

4] Bitwise

  • $bit: Performs bitwise AND, OR and XOR updates of integer values.

Advantages of MongoDB

  • Full cloud-based developer data platform
  • Flexible document schemas
  • Widely supported and code-native data access
  • Change-friendly design
  • Powerful querying and analytics
  • Easy horizontal scale-out with sharding
  • Simple installation
  • Cost-effective
  • Full technical support and documentation

Where is MongoDB used?

  • Big Data
  • Content Management and Delivery
  • Mobile and Social Infrastructure
  • User Data Management
  • Data Hub

--

--