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 Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • MongoDB to Couchbase for Developers, Part 1: Architecture
  • MongoDB to Couchbase: An Introduction to Developers and Experts
  • Manage Hierarchical Data in MongoDB With Spring
  • Why Embedding Pipelines Break at Scale and How Lakehouse Architecture Fixes Them

Trending

  • Optimizing High-Volume REST APIs Using Redis Caching and Spring Boot (With Load Testing Code)
  • Improving DAG Failure Detection in Airflow Using AI Techniques
  • The 7 Pillars of Meeting Design: Transforming Expensive Conversations into Decision Assets
  • Why Your QA Engineer Should Be the Most Stubborn Person on the Team
  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.

By 
Atish A user avatar
Atish A
·
Updated Mar. 16, 18 · Tutorial
Likes (11)
Comment
Save
Tweet
Share
11.1K 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.

Related

  • MongoDB to Couchbase for Developers, Part 1: Architecture
  • MongoDB to Couchbase: An Introduction to Developers and Experts
  • Manage Hierarchical Data in MongoDB With Spring
  • Why Embedding Pipelines Break at Scale and How Lakehouse Architecture Fixes Them

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook