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
How to select documents with values above the average in MongoDB?
To select documents with values above the average in MongoDB, use the aggregation pipeline with $avg to calculate the average, then filter documents using $expr and $gt operators.
Syntax
db.collection.aggregate([
{
$match: {
$expr: {
$gt: [
"$fieldName",
{ $avg: "$fieldName" }
]
}
}
}
]);
Sample Data
db.demo552.insertMany([
{ values: 10 },
{ values: 50 },
{ values: 40 }
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e8e3b1c9e5f92834d7f05ea"),
ObjectId("5e8e3b1f9e5f92834d7f05eb"),
ObjectId("5e8e3b289e5f92834d7f05ec")
]
}
Display all documents from the collection ?
db.demo552.find();
{ "_id": ObjectId("5e8e3b1c9e5f92834d7f05ea"), "values": 10 }
{ "_id": ObjectId("5e8e3b1f9e5f92834d7f05eb"), "values": 50 }
{ "_id": ObjectId("5e8e3b289e5f92834d7f05ec"), "values": 40 }
Method 1: Using $expr with $avg (Recommended)
Select documents where values are above the collection average ?
db.demo552.aggregate([
{
$match: {
$expr: {
$gt: ["$values", { $avg: "$values" }]
}
}
}
]);
{ "_id": ObjectId("5e8e3b1f9e5f92834d7f05eb"), "values": 50 }
{ "_id": ObjectId("5e8e3b289e5f92834d7f05ec"), "values": 40 }
Method 2: Calculate Average First
Calculate the average in a separate operation, then use it in a find query ?
var findAvg = db.demo552.aggregate([
{ "$group": { "_id": null, "Average": { "$avg": "$values" } } }
]).toArray()[0]["Average"];
db.demo552.find({ "values": { "$gt": findAvg } });
{ "_id": ObjectId("5e8e3b1f9e5f92834d7f05eb"), "values": 50 }
{ "_id": ObjectId("5e8e3b289e5f92834d7f05ec"), "values": 40 }
How It Works
The average of values (10, 50, 40) is 33.33. Documents with values 50 and 40 are above this average, so they are returned in the result.
Conclusion
Use $expr with $gt and $avg in a single aggregation pipeline for the most efficient approach. The $avg operator calculates the average dynamically within the query execution.
Advertisements
