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.
Join the DZone community and get the full member experience.
Join For FreeMongoDB 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."
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.
Opinions expressed by DZone contributors are their own.
Comments