DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

Trending

  • Chaining API Requests With API Gateway
  • Writing a Vector Database in a Week in Rust
  • What Is React? A Complete Guide
  • Building a Flask Web Application With Docker: A Step-by-Step Guide

Trending

  • Chaining API Requests With API Gateway
  • Writing a Vector Database in a Week in Rust
  • What Is React? A Complete Guide
  • Building a Flask Web Application With Docker: A Step-by-Step Guide
  1. DZone
  2. Data Engineering
  3. Databases
  4. Expressive Query Language in MongoDB 3.6

Expressive Query Language in MongoDB 3.6

With the release of MongoDB 3.6, fully expressive array updates are now supported. This feature was one of the most requested by developers.

Atish A user avatar by
Atish A
CORE ·
Updated Mar. 16, 18 · Tutorial
Like (11)
Save
Tweet
Share
9.69K Views

Join the DZone community and get the full member experience.

Join For Free

MongoDB 3.6 turned out to be a major release, and brings in powerful features for MongoDB. This release is one step closer to the core mission at MongoDB to "make developers more productive."

Make developers more productive

With the release of MongoDB 3.6, fully expressive array updates are now supported. This feature was one of the most voted-on features and was also one of the most popular questions asked about on StackOverflow.

Let’s understand more about these features.

Fully Expressive Array Updates

Consider a document from the collection; say, orders from an e-commerce inventory:

{
"_id": ObjectId("5a6dd8a2cef6ef7a6ea964ae"),
"customer_id": "B32afb6C",
"cart_items": [{
"id": 1234,
"name": "Wall Sticker",
"price": 79,
"prime": false
}
{
"id": 1235,
"name": "Garden Tool Kit",
"price": 525,
"prime": true
}
]
}

Use case: You want to allocate a 10% discount on all items in the cart for customer B32afb6C.

In earlier versions, either you need to update one element at a time from the cart_items array or fetch the entire document, modify the cart_items array, and then save the modified document.

With the revised query logic in MongoDB 3.6 and the help of the $[] operator, you can update all cart_items in a single query.

Let’s go through the example for $[] operator in detail.

Update All Elements in the Array Using the $[] Operator

Using the $[] operator, you can update all items in the cart_items array in a single update query for the customer ID B32afb6C. As per the use case, you will apply a 10% discount for the entire array, as follows:

db.orders.update({
"customer_id": "B32afb6C"
}, {
$mul: {
"cart_items.$[].price": 0.9
}
})

You should see the updated document with the 10% discount applied for each item in the cart_items array:

{
"_id": ObjectId("5a6dd8a2cef6ef7a6ea964ae"),
"customer_id": "B32afb6C",
"cart_items": [{
"id": 1234,
"name": "Wall Sticker",
"price": 71.10000000000001,
"prime": false
},
{
"id": 1235,
"name": "Garden Tool Kit",
"price": 472.5,
"prime": true
}
]
}

Update Specific Elements From the Array Using $[<identifiler>]

In the previous example, you applied the 10% discount on the entire array. However, you might want to update specific elements that satisfy certain conditions, say, apply the 10% discount only to the items with the attribute prime: true.

Using the $[<identifier>] operator along with arrayFilters, you will be able to update the elements that satisfy the condition listed above. Your query should look like this:

db.orders.update({
"customer_id": "B32afb6C"
}, {
$mul: {
"cart_items.$[item].price": 0.9
}
}, {
arrayFilters: [{
"item.prime": true
}]
})

The result will be that each element with prime: true will have a 10% discount applied:

{
"_id": ObjectId("5a6dd8a2cef6ef7a6ea964ae"),
"customer_id": "B32afb6C",
"cart_items": [{
"id": 1234,
"name": "Wall Sticker",
"price": 79,
"prime": false
},
{
"id": 1235,
"name": "Garden Tool Kit",
"price": 472.5,
"prime": true
}
]
}

Compare Two Fields From a Single Document

Consider the following documents from the Movies collection in the IMDB database:

{
"_id": ObjectId("5a88538e7fd2270a1908a13a"),
"title": "Okja",
"year": "2017",
"genres": [
" Drama",
"Science fiction"
],
"director": "Bong Joon-ho",
"imdb": 74,
"rottenTommatos": 85,
"metacritic": 80,
"languages": [
"English",
"Korean"
],
"initial release": ISODate("2017-05-19T09:08:58Z"),
"viewers_ratings": [89, 74, 80, 76, 67, 87, 75]
]
} {
"_id": ObjectId("5a886b597fd2270a1908a13b"),
"title": "3 Geezers!",
"year": "2013",
"genres": [
"Comedy"
],
"director": "Michelle Schumacher",
"imdb": 33,
"rottenTommatos": 2.1,
"metacritic": 9,
"languages": [
"English"
],
"initial release": ISODate("2013-05-22T00:00:00Z"),
"viewers_ratings": [30, 46, 55, 25, 26, 47, 65]
}

Use-case: Find all the movies from the Movies collection where the meta-critic ratings are greater than the IMDB ratings.

With the query logic in old versions, you would have to use the $gt operator in the find query with a condition like meta-critic ratings greater than IMDB rating. However, the $gt operator allows comparison between the values of a single field. You will not be able to compare the values of two different fields of a single document.

With the revised query logic in MongoDB 3.6, you can compare two fields from a single document using the $expr operator. With this operator, you can leverage the capability of the aggregation expressions within the CRUD operations.

Compare 2 Fields in the Find Query Using the $expr Operator

The following query in MongoDB 3.6 will return all the English movies with reviews where the meta-critic ratings are greater than the IMDB ratings:

db.movies.find({
"languages": "English"
$expr: {
$gt: ["$metacritic", "$imdb"]
}
})

You will receive a single document from the movies collection using this query:

{
"_id": ObjectId("5a88538e7fd2270a1908a13a"),
"title": "Okja",
"year": "2017",
"genres": [
" Drama",
"Science fiction"
],
"director": "Bong Joon-ho",
"imdb": 74,
"rottenTommatos": 85,
"metacritic": 80,
"languages": [
"English",
"Korean"
],
"initial release": ISODate("2017-05-19T09:08:58Z"),
"viewers_ratings": [89, 74, 80, 76, 67, 87, 75]
]
}

Compare 2 Fields in the Update Query Using the $expr Operator

In the following query, you will tag all movies with popular:true if the average viewers_ratings is greater than 70:

db.movies.updateMany({
$expr: {
$gt: [{
$avg: ["$viewers_ratings"]
}, 70]
}
}, {
$set: {
popular: true
}
})

This update operation sets a popularity tag for the following movie:

{
"_id": ObjectId("5a88538e7fd2270a1908a13a"),
"title": "Okja",
"year": "2017",
"genres": [
" Drama",
"Science fiction"
],
"director": "Bong Joon-ho",
"imdb": 74,
"rottenTommatos": 85,
"metacritic": 75,
"languages": [
"English",
"Korean"
],
"initial release": ISODate("2017-05-19T09:08:58Z"),
"viewers_ratings": [
89, 74, 80, 76, 67, 87, 75
],
"popular": true
}

Summary

MongoDB 3.6 introduces new possibilities for data models that have arrays. You can modify complex and nested array elements in MongoDB 3.6 using the new operators. Download and explore MongoDB 3.6 here.

You can follow me at @AtishAndare.



If you enjoyed this article and want to learn more about MongoDB, check out this collection of tutorials and articles on all things MongoDB.

Database MongoDB Query language Operator (extension) Data structure Document

Opinions expressed by DZone contributors are their own.

Trending

  • Chaining API Requests With API Gateway
  • Writing a Vector Database in a Week in Rust
  • What Is React? A Complete Guide
  • Building a Flask Web Application With Docker: A Step-by-Step Guide

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: