- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 }
Advertisements