How to create a performance system that count tags across a large dynamic dataset in MongoDB?


Create an index and then use explain(). Let us create a collection with documents −

> db.demo278.ensureIndex({"Subjects":1});
{
   "createdCollectionAutomatically" : true,
   "numIndexesBefore" : 1,
   "numIndexesAfter" : 2,
   "ok" : 1
}
> db.demo278.insertOne({"Subjects":["MySQL","MongoDB","Java"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e49096edd099650a5401a55")
}
> db.demo278.insertOne({"Subjects":["C","C++"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e490978dd099650a5401a56")
}
> db.demo278.insertOne({"Subjects":["Spring","Hibernate"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e490984dd099650a5401a57")
}

Display all documents from a collection with the help of find() method −

> db.demo278.find();

This will produce the following output −

{ "_id" : ObjectId("5e49096edd099650a5401a55"), "Subjects" : [ "MySQL", "MongoDB", "Java" ] }
{ "_id" : ObjectId("5e490978dd099650a5401a56"), "Subjects" : [ "C", "C++" ] }
{ "_id" : ObjectId("5e490984dd099650a5401a57"), "Subjects" : [ "Spring", "Hibernate" ] }

Here is the query to check performance −

> db.demo278.find({Subjects:{$in:["Spring","MongoDB"]}}).explain();

This will produce the following output −

{
   "queryPlanner" : {
      "plannerVersion" : 1,
      "namespace" : "test.demo278",
      "indexFilterSet" : false,
      "parsedQuery" : {
         "Subjects" : {
            "$in" : [
               "MongoDB",
               "Spring"
            ]
         }
      },
      "winningPlan" : {
         "stage" : "FETCH",
         "inputStage" : {
            "stage" : "IXSCAN",
            "keyPattern" : {
               "Subjects" : 1
            },
            "indexName" : "Subjects_1",
            "isMultiKey" : true,
            "multiKeyPaths" : {
               "Subjects" : [
                  "Subjects"
               ]
            },
            "isUnique" : false,
            "isSparse" : false,
            "isPartial" : false,
            "indexVersion" : 2,
            "direction" : "forward",
            "indexBounds" : {
               "Subjects" : [
                  "[\"MongoDB\", \"MongoDB\"]",
                  "[\"Spring\", \"Spring\"]"
               ]
            }
         }
      },
      "rejectedPlans" : [ ]
   },
   "serverInfo" : {
      "host" : "DESKTOP-QN2RB3H",
      "port" : 27017,
      "version" : "4.0.5",
      "gitVersion" : "3739429dd92b92d1b0ab120911a23d50bf03c412"
   },
   "ok" : 1
}

Updated on: 31-Mar-2020

34 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements