The Wayback Machine - https://web.archive.org/web/20240927172714/https://www.geeksforgeeks.org/mongodb-positional-operator/
Open In App

MongoDB – Positional Operator ($)

Last Updated : 21 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

MongoDB provides a variety of array update operators to modify the values within array fields in documents. One such operator is the positional operator $. This operator allows us to update an element in an array without explicitly specifying the position of that element. In this article, We will learn about the Positional Operator($) in MongoDB in detail.

MongoDB Positional Operator

MongoDB provides different types of array update operators to update the values of the array fields in the documents and the positional operator() is one of them.

The $ operator can be used with arrays containing embedded documents which allows us to update fields within those nested documents efficiently.

Syntax:

{ "<array>.$" : value }
  • We cannot use the $ operator with upsert operations. If we use $ operator with upsert operations, then the insert will use the $ as a field name in the inserted document.
  • This operator cannot use for those queries which traverse more than one array because the replacement for the $ placeholder is a single value.
  • When we use the $ operator with $unset operator then $ operator does not remove the matching item from the array, but rather sets it to null.
  • When a query matches the array with the help of negation operators like $not, $ne, or $nin, then you cannot use the $ operator to update the values of that array. And if the negated part of the query is present inside of an $elemMatch expression then we can use the positional $ operator to update this field.
  • When we use this operator with an update operation like db.collection.update() and db.collection.findAndModify() then the $ operator works as a placeholder for the first item that matches the query document and the array field is necessary to appear as a part of the query document.

Examples of MongoDB Positional Operator

In the following examples, we are working with called contributor which contains various information in terms of documents as shown below:

Output:

Example 1: Update All Elements in an Array

In this example, we are updating the first item whose value is “Python” to “Ruby” in the language field with the help of $ operator, because we don’t know the position of the item in the array.

db.contributor.updateOne({name: "Rohit", language: "Python"}, 
{$set: {"language.$": "Ruby"}})

Output:

Here, the $ operator is working as a placeholder for the first match of the update query document.

Note: The array field must be the part of the query.

Example 2: Update All Documents in an Array

In this example, we are updating an array that contains embedded documents with the help of $ operator and to access embedded document fields we use dot notation. Or in other words, we are updating the value of tArticle field from 60 to 100.

db.contributor.updateOne({name: "Rohit", "articles.language": "C#"}, 
{$set: {"articles.$.tArticles": 100}})

Output:

Example 3: Update Nested Arrays 

In this example, we are updating the value of the tArticles field in the first embedded document that has a pArticles field with a value greater than 90.

db.contributor.updateOne({name: "Sumit", articles: {$elemMatch:
{pArticles: {$gt: 30}}}},
{$set: {"articles.$.tArticles": 200}})

Output:

Update-Nested-Arrays

Conclusion

The MongoDB positional operator $ is a powerful tool for updating elements within arrays when the exact position is unknown. By acting as a placeholder for the first matching element, it simplifies the update process. However, it comes with limitations such as not being usable with upsert operations or queries involving negation operators. Understanding these nuances can help effectively use the $ operator for various array update operations in MongoDB.

FAQs on MongoDB Positional Operator

1. Can the $ operator be used with upsert operations?

No, the $ operator cannot be used with upsert operations. If you attempt to use it, MongoDB will treat $ as a field name in the inserted document.

2. How does the $ operator interact with the $unset operator?

When used with the $unset operator, the $ operator does not remove the matching item from the array but instead sets it to null.

3. Can the $ operator update arrays when using negation operators like $not, $ne, or $nin?

No, the $ operator cannot be used to update arrays when the query matches using negation operators like $not, $ne, or $nin. However, if the negation part is within an $elemMatch expression, you can use the $ operator.


Previous Article
Next Article

Similar Reads

MongoDB All Positional Operator ($[])
The MongoDB $[] positional operator is a powerful tool used to update all elements in an array that match a specified condition. When working with arrays in MongoDB, this operator helps identify and modify every element that meets the query criteria. In this article, We will learn about the MongoDB All Positional Operator ($[]) by understanding var
4 min read
Connect MongoDB (AWS) from Local Machine using WinSCP and MongoDB Compass
Pre-requisite: AWS and MongoDB In this article, we are going to connect to the Mongo database of the AWS Ubuntu Server instance using WinSCP and learn how to get connected to the server from your local machine using MongoDB Compass.  If you haven't installed a MongoDB server in your AWS EC2 instance then follow the steps present in this article and
4 min read
How to Integrate MongoDB Atlas and Segment using MongoDB Stitch
Data integration has become a crucial component of modern business strategies, allowing companies to enhance the power of data for informed decision-making. According to a recent survey, 85% of businesses believe that integrating data across multiple platforms is important for their success. In this article, We will learn about What is MongoDB Stit
5 min read
MongoDB - Delete Multiple Documents Using MongoDB Shell
The db.collection.deleteMany() method is used to delete multiple documents from a collection in Mongo Shell. This method deletes multiple documents from the collection according to the filter. The deleteMany() is a Mongo shell method, which can delete multiple documents. This method can be used in multi-document transactions. If you use this method
2 min read
Connect MongoDB Atlas Cluster to MongoDB Compass
MongoDB Compass is a free GUI for MongoDB. You might want to connect MongoDB Atlas Cluster to MongoDB Compass to take benefit of the GUI model for database administration. This guide explains how to connect MongoDB Atlas Cluster to MongoDB Compass. The connection process involves obtaining a connection string from MongoDB Atlas, configuring MongoDB
4 min read
MongoDB Shell vs MongoDB Node.JS Driver
MongoDB Shell and the MongoDB Node.js Driver are both tools for interacting with MongoDB, but they serve different purposes and are used in different contexts. Here's a comparison of the two: MongoDB Node.JS DriverA Node.js package called the MongoDB Node.js Driver enables programmatic communication between applications and MongoDB databases. Throu
4 min read
MongoDB Compass vs MongoDB Atlas
MongoDB is a popular NoSQL database known for flexibility and scalability. MongoDB Compass offers a graphical interface for managing databases visually while MongoDB Atlas is a cloud-based service for automated management and scaling of MongoDB databases. In this article, We will learn about the in-depth understanding of the difference between the
5 min read
MongoDB AND operator ( $and )
MongoDB provides different types of logical query operators and $and operator is one of them. This operator is used to perform logical AND operation on the array of one or more expressions and select or retrieve only those documents that match all the given expression in the array. You can use this operator in methods like find(), update(), etc. ac
2 min read
MongoDB NOT operator ( $not )
MongoDB provides different types of logical query operators and $not operator is one of them. This operator is used to perform logical NOT operation on the specified operator expressions and select or retrieve only those documents that do not match the given operator expression. It also includes those documents that don't contain the field. You can
2 min read
MongoDB OR operator ( $or )
MongoDB provides different types of logical query operators and $or operator is one of them. This operator is used to perform logical OR operation on the array of two or more expressions and select or retrieve only those documents that match at least one of the given expression in the array. You can use this operator in methods like find(), update(
2 min read
MongoDB NOR operator ( $nor )
MongoDB provides different types of logical query operators and $nor operator is one of them. This operator is used to perform logical NOR operation on the array of one or more expressions and select or retrieve only those documents that do not match all the given expression in the array. You can use this operator in methods like find(), update(),
2 min read
MongoDB - Current Date Operator ($currentDate)
MongoDB provides different types of field update operators to update the values of the fields of the documents and $currentDate operator is one of them. This operator is used to set the value of a field to the current date (either as a timestamp or as a Date). The default type of $currentDate operator is a Date. This operator can also work with emb
2 min read
MongoDB $ln Operator
MongoDB provides different types of arithmetic expression operators that are used in the aggregation pipeline stages and $ln operator is one of them. This operator is used to find the natural logarithm of a number and returns the result as a double. Syntax: { $ln: <number> } Here, the number is a valid expression until it resolves to a non- n
1 min read
MongoDB $sqrt Operator
MongoDB provides different types of arithmetic expression operators that are used in the aggregation pipeline stages $sqrt operator is one of them. This operator is used to find the square root of a positive number and returns the result as a double. Syntax: { $sqrt: <number> } Here, the number is a valid expression until it resolves to a non
2 min read
MongoDB $mod Operator
MongoDB provides different types of arithmetic expression operators that are used in the aggregation pipeline stages and $mod operator is one of them. This operator is used to divide one number by another number and return the remainder. Syntax: { $mod: [ <expression1>, <expression2> ] } Here, in this operator, the arguments passed in a
1 min read
MongoDB - $ne Operator
MongoDB $ne or "not equals" operator is one of the comparison operators. The $ne operator selects those documents where the field value is not equal to the given value. It also includes those documents that do not contain the specified field. You can use this operator in methods like find(), update(), etc. as per your requirement. Syntax{field: {$n
2 min read
MongoDB - $nin Operator
MongoDB $nin or " not in" is one of the comparison query operators. The $nin operator selects those documents where the field value is not equal to any of the given values in the array and the field that does not exist. You can use this operator in methods like find(), update(), etc. according to your requirements. Syntax{field: {$nin: [value1, val
2 min read
MongoDB - $max Operator
MongoDB $max or maximum operator is one of the field update operators. $max operator updates the field with the specified value if the specified value is greater than the current value. Important Points This operator will compare the values of different data types according to the BSON comparison order.You can also use this operator in embedded/nes
3 min read
MongoDB - $min operator
MongoDB $min or minimum operator is one of the field update operators. $min operator updates the field with the specified value if the specified value is less than the current value. The $min operator will compare the values of different data types according to the BSON comparison order. This operator can also be used in embedded/nested documents u
3 min read
MongoDB - $inc Operator
MongoDB $inc or increment operator is a type of field update operator. $inc operator increases the values of the fields to the specified amount or increases the field by the given value. Important PointsThis operator accepts positive and negative values.If the given field does not exist, then this operator will create a field and set the value of t
2 min read
MongoDB - $lt Operator
MongoDB $lt operator or less than operator is one of the comparison operators. The $lt operator selects the documents with a value less than (<) the given value. You can use this operator in methods like, find(), update(), etc. as per your requirements. Syntax{field: {$lt: value}}MongoDB $lt Operator ExampleIn the following examples, we are work
2 min read
MongoDB - $lte Operator
MongoDB $lte Operator is one of the comparison operators. $lte operator selects those documents where the field value is less than equal to (<=) the given value. This operator can be used in methods like find(), update(), etc. according to your requirements.. Syntax{field: {$lte: value}}MongoDB $lte Operator ExampleIn the following examples, we
2 min read
How to use the $lookup operator in aggregation pipelines in MongoDB?
One of the essential stages of the Aggregation Pipeline is the $lookup. It enables us to accomplish a left outer join between two collections. This step is quite beneficial when we have to compose data from different collections into a single document. The Aggregation Pipeline in MongoDB is a robust tool that allows us to manipulate and analyze dat
4 min read
MongoDB $gt Operator
MongoDB $gt operator selects documents where the value of a field is greater than a specified value. $gt Operator in MongoDBThe $gt operator in MongoDB is a comparison operator. It is used to find documents where the value in the field is greater than(>) a given value. This operator can be used with other methods like find, update, etc. accordin
2 min read
MongoDB - $concat Operator
The $concat operator in MongoDB is a useful tool for string manipulation within aggregation pipelines. It allows us to concatenate strings or expressions to create new fields or modify existing ones. In this article, We will learn about the $concat operator in MongoDB by understanding various examples in detail. MongoDB - $concat OperatorThe $conca
3 min read
MongoDB $subtract Operator
MongoDB $subtract operator is a powerful tool in the aggregation pipeline that allows users to perform subtraction operations on numbers or dates. In this article, We will learn about MongoDB $subtract Operator by understanding various examples in detail. MongoDB $subtract OperatorMongoDB provides different types of arithmetic expression operators
3 min read
MongoDB $addToSet Operator
The $addToSet operator in MongoDB allows us to add elements to an array field if they are not already present and ensure that the array contains unique values. In this article, We will learn about the MongoDB $addToSet Operator by understanding various examples in detail. $addToSet Operator in MongoDBThe $addToSet operator in MongoDB is used to add
3 min read
MongoDB - Rename Operator ($rename)
MongoDB $rename operator is a powerful tool for updating field names within documents which ensures data consistency and structure. This operator allows developers to rename fields in a MongoDB collection, including those nested within documents or arrays. In this article, We will learn about the MongoDB $rename by understanding various examples in
4 min read
MongoDB $arrayElemAt Operator
MongoDB $arrayElemAt operator is a key component of the aggregation framework, allowing users to retrieve specific elements from arrays within their documents. In this article, We will learn about the MongoDB $arrayElemAt by understanding various examples in detail and so on. MongoDB $arrayElemAtMongoDB provides different types of array expression
3 min read
MongoDB - $setOnInsert Operator
The $setOnInsert operator in MongoDB is a powerful tool used in updating operations with the upsert option. It allows us to specify values that should be set only when a new document is inserted. In this article, we will learn about the $setOnInsert Operator in MongoDB in detail and so on. MongoDB $setOnInsert OperatorMongoDB $setOnInsert Operator
4 min read