Syntax error How to select documents with values above the average in MongoDB?

How to select documents with values above the average in MongoDB?



Use aggregate() in MongoDB to select documents with values above the average. To find the average, use $avg in MongoDB.

Let us create a collection with documents −

> db.demo552.insertOne({values:10});{
   "acknowledged" : true, "insertedId" : ObjectId("5e8e3b1c9e5f92834d7f05ea")
}
> db.demo552.insertOne({values:50});{
   "acknowledged" : true, "insertedId" : ObjectId("5e8e3b1f9e5f92834d7f05eb")
}
> db.demo552.insertOne({values:40});{
   "acknowledged" : true, "insertedId" : ObjectId("5e8e3b289e5f92834d7f05ec")
}

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

> db.demo552.find();

This will produce the following output −

{ "_id" : ObjectId("5e8e3b1c9e5f92834d7f05ea"), "values" : 10 }
{ "_id" : ObjectId("5e8e3b1f9e5f92834d7f05eb"), "values" : 50 }
{ "_id" : ObjectId("5e8e3b289e5f92834d7f05ec"), "values" : 40 }

Following is the query to select documents with values above the average −

> var findAvg = db.demo552.aggregate([
...    { "$group": { "_id": "null", Average: { "$avg": "$values"} }}
... ]).toArray()[0]["Average"];
> db.demo552.find({ "values": { "$gt": findAvg } })

This will produce the following output −

{ "_id" : ObjectId("5e8e3b1f9e5f92834d7f05eb"), "values" : 50 }
{ "_id" : ObjectId("5e8e3b289e5f92834d7f05ec"), "values" : 40 }
Updated on: 2020-05-14T07:56:34+05:30

465 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements