Learn MongoDB With Me (Part 3)
This is the continuation of a series exploring Indexes in MongoDB. We will be discussing various MongoDB indexes that we can perform on our data.
Join the DZone community and get the full member experience.
Join For Freethis is the third article in the "learn mongodb with me" series. if you haven't read my previous posts on this topic, i strongly recommend you to find part 1 here and part 2 here . this is the continuation of a series exploring indexes in mongodb. we will be discussing various mongodb indexes that we can perform on our data. i hope you will find this post useful. thanks for reading.
indexes in mongodb
let's import a new collection,
products
, first.
[
{
"id":2,
"name":"an ice sculpture",
"price":12.50,
"tags":[
"cold",
"ice"
],
"dimensions":{
"length":7.0,
"width":12.0,
"height":9.5
},
"warehouselocation":{
"latitude":-78.75,
"longitude":20.4
}
},
{
"id":3,
"name":"a blue mouse",
"price":25.50,
"dimensions":{
"length":3.1,
"width":1.0,
"height":1.0
},
"warehouselocation":{
"latitude":54.4,
"longitude":-32.7
}
},
{
"id":4,
"name":"keyboard",
"price":15.50,
"dimensions":{
"length":1.1,
"width":1.0,
"height":1.0
},
"warehouselocation":{
"latitude":24.4,
"longitude":-42.7
}
},
{
"id":5,
"name":"doll",
"price":10.50,
"dimensions":{
"length":5.1,
"width":1.0,
"height":7.0
},
"warehouselocation":{
"latitude":64.4,
"longitude":-82.7
}
},
{
"id":6,
"name":"wallet",
"price":5.50,
"dimensions":{
"length":1.1,
"width":1.0,
"height":1.0
},
"warehouselocation":{
"latitude":24.4,
"longitude":-12.7
}
}
]
please note that these are just dummy data, and they may sound illogical to you.
c:\program files\mongodb\server\3.4\bin>mongoimport --db mylearning --collection products --jsonarray --file products.json
2018-03-06t16:48:34.440+0530 connected to: localhost
2018-03-06t16:48:34.607+0530 imported 5 documents
c:\program files\mongodb\server\3.4\bin>
if you don't know how the
import
command works, please read my
previous posts
, in which we saw simple indexes. now that we have the data, let's go perform indexes.
single-key indexes
in one of my previous posts in this series of articles, i mentioned simple indexes. in this article, we are not going to talk about that. instead, we will explore other indexing options that mongodb has. let's learn about multi-key indexes.
multi-key indexes or compound indexes
as the name implies, we are actually going to set indexes with more than one key element. on our products collection, we have some product documents right, what we a user needs to filter the same with the price and warehouse location. yeah, we need to build a query.
mongodb enterprise > db.products.find({
... "price: {$lte: 16},
2018-03-06t17:10:15.005+0530 e query [thread1] syntaxerror: unterminated string literal @(shell):2:0
mongodb enterprise > db.products.find({
... "price": {$lte: 16},
... "warehouselocation.latitude": {$gte: 60}
... })
{ "_id" : objectid("5a9e790a1ae1f955c1a70c4a"), "id" : 5, "name" : "doll", "price" : 10.5, "dimensions" : { "length" : 5.1, "width" : 1, "height" : 7 }, "warehouselocation" : { "latitude" : 64.4, "longitude" : -82.7 } }
mongodb enterprise >
we have got one entry according to our search,
"price": {$lte: 16}
and
"warehouselocation.latitude": {$gte: 60}
that's cool. now, let's try to find out the execution status for the same.
please be noted that we have used
$lte
and
$gte
, which stands for "less than or equal to" and "greater than or equal to." remember what i have told you before: mongo shell is cool and we can do anything with it. let's find out the examined elements count for our preceding find query now.
db.products.find({ "price": {$lte: 16}, "warehouselocation.latitude": {$gte: 60} }).explain("executionstats")
and if your query is correct, you will be getting a result as preceding.
"queryplanner" : {
"plannerversion" : 1,
"namespace" : "mylearning.products",
"indexfilterset" : false,
"parsedquery" : {
"$and" : [
{
"price" : {
"$lte" : 16
}
},
{
"warehouselocation.latitude" : {
"$gte" : 60
}
}
]
},
"winningplan" : {
"stage" : "collscan",
"filter" : {
"$and" : [
{
"price" : {
"$lte" : 16
}
},
{
"warehouselocation.latitude" : {
"$gte" : 60
}
}
]
},
"direction" : "forward"
},
"rejectedplans" : [ ]
},
"executionstats" : {
"executionsuccess" : true,
"nreturned" : 1,
"executiontimemillis" : 107,
"totalkeysexamined" : 0,
"totaldocsexamined" : 5,
"executionstages" : {
"stage" : "collscan",
"filter" : {
"$and" : [
{
"price" : {
"$lte" : 16
}
},
{
"warehouselocation.latitude" : {
"$gte" : 60
}
}
]
},
"nreturned" : 1,
"executiontimemillisestimate" : 0,
"works" : 7,
"advanced" : 1,
"needtime" : 5,
"needyield" : 0,
"savestate" : 0,
"restorestate" : 0,
"iseof" : 1,
"invalidates" : 0,
"direction" : "forward",
"docsexamined" : 5
}
},
"serverinfo" : {
"host" : "pc292716",
"port" : 27017,
"version" : "3.4.9",
"gitversion" : "876ebee8c7dd0e2d992f36a848ff4dc50ee6603e"
},
"ok" : 1
}
you might have already noticed the value we have for
totaldocsexamined
. if you haven't, please check now. in my case, it is 5, which means that the query just examined all the records we have. ah, that sounds bad, right? what if we have millions of records in our collection? how long is it gonna take to fetch the results?
mongodb enterprise > db.products.createindex({price:1, "warehouselocation.latitude":1})
{
"createdcollectionautomatically" : false,
"numindexesbefore" : 1,
"numindexesafter" : 2,
"ok" : 1
}
run your previous query now and find out what the value of docs examined is.
mongodb enterprise > db.products.find({ "price": {$lte: 16}, "warehouselocation.latitude": {$gte: 60} }).explain("executionstats")
{
"queryplanner" : {
"plannerversion" : 1,
"namespace" : "mylearning.products",
"indexfilterset" : false,
"parsedquery" : {
"$and" : [
{
"price" : {
"$lte" : 16
}
},
{
"warehouselocation.latitude" : {
"$gte" : 60
}
}
]
},
"winningplan" : {
"stage" : "fetch",
"inputstage" : {
"stage" : "ixscan",
"keypattern" : {
"price" : 1,
"warehouselocation.latitude" : 1
},
"indexname" : "price_1_warehouselocation.latitude_1",
"ismultikey" : false,
"multikeypaths" : {
"price" : [ ],
"warehouselocation.latitude" : [ ]
},
"isunique" : false,
"issparse" : false,
"ispartial" : false,
"indexversion" : 2,
"direction" : "forward",
"indexbounds" : {
"price" : [
"[-inf.0, 16.0]"
],
"warehouselocation.latitude" : [
"[60.0, inf.0]"
]
}
}
},
"rejectedplans" : [ ]
},
"executionstats" : {
"executionsuccess" : true,
"nreturned" : 1,
"executiontimemillis" : 1089,
"totalkeysexamined" : 5,
"totaldocsexamined" : 1,
"executionstages" : {
"stage" : "fetch",
"nreturned" : 1,
"executiontimemillisestimate" : 310,
"works" : 5,
"advanced" : 1,
"needtime" : 3,
"needyield" : 0,
"savestate" : 2,
"restorestate" : 2,
"iseof" : 1,
"invalidates" : 0,
"docsexamined" : 1,
"alreadyhasobj" : 0,
"inputstage" : {
"stage" : "ixscan",
"nreturned" : 1,
"executiontimemillisestimate" : 270,
"works" : 5,
"advanced" : 1,
"needtime" : 3,
"needyield" : 0,
"savestate" : 2,
"restorestate" : 2,
"iseof" : 1,
"invalidates" : 0,
"keypattern" : {
"price" : 1,
"warehouselocation.latitude" : 1
},
"indexname" : "price_1_warehouselocation.latitude_1",
"ismultikey" : false,
"multikeypaths" : {
"price" : [ ],
"warehouselocation.latitude" : [ ]
},
"isunique" : false,
"issparse" : false,
"ispartial" : false,
"indexversion" : 2,
"direction" : "forward",
"indexbounds" : {
"price" : [
"[-inf.0, 16.0]"
],
"warehouselocation.latitude" : [
"[60.0, inf.0]"
]
},
"keysexamined" : 5,
"seeks" : 4,
"dupstested" : 0,
"dupsdropped" : 0,
"seeninvalidated" : 0
}
}
},
"serverinfo" : {
"host" : "pc292716",
"port" : 27017,
"version" : "3.4.9",
"gitversion" : "876ebee8c7dd0e2d992f36a848ff4dc50ee6603e"
},
"ok" : 1
}
mongodb enterprise > db.products.find({ "price": {$lte: 16}, "warehouselocation.latitude": {$gte: 60} })
{ "_id" : objectid("5a9e790a1ae1f955c1a70c4a"), "id" : 5, "name" : "doll", "price" : 10.5, "dimensions" : { "length" : 5.1, "width" : 1, "height" : 7 }, "warehouselocation" : { "latitude" : 64.4, "longitude" : -82.7 } }
mongodb enterprise >
yeah! we got
"docsexamined" : 1
. way to go. go create some indexes on your topmost queries, you can definitely see some magic over there. you can create up to 64 indexes on a collection in mongodb, but you may need to create only a few, only on your top result queries. whenever you are facing any performance issues on any queries, consider that it needs some tuning and definitely an index. there are so many other complex indexes, but widely used indexes are single key index and compound index.
if you enjoyed this article and want to learn more about mongodb, check out this collection of tutorials and articles on all things mongodb.
Published at DZone with permission of Sibeesh Venu, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Trending
-
Why You Should Consider Using React Router V6: An Overview of Changes
-
Low Code vs. Traditional Development: A Comprehensive Comparison
-
Implementing RBAC in Quarkus
-
JSON to PDF Magic: Harnessing LaTeX and JSON for Effortless Customization and Dynamic PDF Generation
Comments