Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
MongoDB query for ranking / search count?
To implement ranking or search count in MongoDB, use the aggregation pipeline with $setIntersection to find matching elements and $divide to calculate a relevance score based on the ratio of matched terms to total document elements.
Syntax
db.collection.aggregate([
{ "$match": { "fieldName": { "$in": searchArray } } },
{ "$addFields": {
"rankScore": {
"$divide": [
{ "$size": { "$setIntersection": ["$fieldName", searchArray] } },
{ "$size": "$fieldName" }
]
}
}},
{ "$sort": { "rankScore": -1 } }
])
Sample Data
db.demo120.insertMany([
{
"Name": "Chris",
"Subjects": ["MySQL", "MongoDB", "Java", "Python"]
},
{
"Name": "Bob",
"Subjects": ["C", "MongoDB"]
}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e2f11aed8f64a552dae6365"),
ObjectId("5e2f11afd8f64a552dae6366")
]
}
Display Sample Data
db.demo120.find();
{ "_id": ObjectId("5e2f11aed8f64a552dae6365"), "Name": "Chris", "Subjects": ["MySQL", "MongoDB", "Java", "Python"] }
{ "_id": ObjectId("5e2f11afd8f64a552dae6366"), "Name": "Bob", "Subjects": ["C", "MongoDB"] }
Example: Ranking Query
var searchTerms = ["MySQL", "Java", "MongoDB"];
db.demo120.aggregate([
{ "$match": { "Subjects": { "$in": searchTerms } } },
{
"$addFields": {
"RankSearch": {
"$divide": [
{ "$size": { "$setIntersection": ["$Subjects", searchTerms] } },
{ "$size": "$Subjects" }
]
}
}
},
{ "$sort": { "RankSearch": -1 } }
]);
{ "_id": ObjectId("5e2f11aed8f64a552dae6365"), "Name": "Chris", "Subjects": ["MySQL", "MongoDB", "Java", "Python"], "RankSearch": 0.75 }
{ "_id": ObjectId("5e2f11afd8f64a552dae6366"), "Name": "Bob", "Subjects": ["C", "MongoDB"], "RankSearch": 0.5 }
How It Works
-
$setIntersectionfinds common elements between document array and search terms -
$dividecalculates relevance score: (matches / total_document_elements) -
$sortorders results by highest relevance score first - Chris scores 0.75 (3 matches out of 4 subjects), Bob scores 0.5 (1 match out of 2 subjects)
Conclusion
MongoDB's aggregation pipeline enables sophisticated ranking by calculating relevance scores using $setIntersection and $divide. This approach ranks documents based on the percentage of matching elements, providing meaningful search results ordered by relevance.
Advertisements
