MongoDB query for ranking / search count?


For this, use aggregate() in MongoDB. Let us create a collection with documents −

> db.demo120.insertOne(
...    {
...       'Name': 'Chris',
...       'Subjects': [ 'MySQL', 'MongoDB', 'Java', 'Python' ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2f11aed8f64a552dae6365")
}
> db.demo120.insertOne(
...    {
...       'Name': 'Bob',
...       'Subjects': [ 'C', 'MongoDB' ]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2f11afd8f64a552dae6366")
}

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

> db.demo120.find();

This will produce the following output −

{ "_id" : ObjectId("5e2f11aed8f64a552dae6365"), "Name" : "Chris", "Subjects" : [ "MySQL", "MongoDB", "Java", "Python" ] }
{ "_id" : ObjectId("5e2f11afd8f64a552dae6366"), "Name" : "Bob", "Subjects" : [ "C", "MongoDB" ] }

Following is the query for MongoDB ranking / search count −

> var s = ['MySQL', 'Java', 'MongoDB'];
> db.demo120.aggregate([
...    { "$match": { "Subjects": { "$in": s } } },
...    {
...       "$addFields": {
...          "RankSearch": {
...             "$divide": [
...                { "$size": { "$setIntersection": ["$Subjects",s] } },
...                { "$size": "$Subjects" }
...             ]
...          }
...       }
...    },
...    { "$sort": { "RankSearch": -1 } }
... ])

This will produce the following output −

{ "_id" : ObjectId("5e2f11aed8f64a552dae6365"), "Name" : "Chris", "Subjects" : [ "MySQL", "MongoDB", "Java", "Python" ], "RankSearch" : 0.75 }
{ "_id" : ObjectId("5e2f11afd8f64a552dae6366"), "Name" : "Bob", "Subjects" : [ "C", "MongoDB" ], "RankSearch" : 0.5 }

Updated on: 31-Mar-2020

340 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements