Search code examples
jsondatabasemongodbbson

MongoDb: Retrieve all documents higher than the average value of a column


I have created a collection using this piece of code.

db.createCollection("item", {
    validator: {
        $jsonSchema: {
            bsonType: "object",
            required: ["_id", "item_name", "unit_price"],
            properties: {
                _id: {
                    bsonType: "string",
                    description: "must be a string and is required",
                    minLength: 3,
                    maxLength: 5,
                    pattern: "I[0-9]*$"
                },
                item_name: {
                    bsonType: "string",
                    description: "must be a string and is required"
                },
                unit_price: {
                    bsonType: "double"
                }
            }
        }
    },
    validationLevel: "moderate"
})

and I have inserted records in the Item collection. Now I wish to list the items whose "unit_price" is less than the average price of all items. What I have tried is

db.item.aggregate([{
    $group: {
        _id: null,
        averageUnitPrice: {
            $avg: "$unit_price"
        }
    }
}])

I have tried to use the above piece of code but I am not able to figure out how to take this average and use it to retrieve the documents higher than averageUnitPrice. Any help is highly appreciated!! Thanks a tonn!!!.


Solution

  • So I finally figured it out. This query will give me the average and the list of items which are less than the average value.

    db.item.aggregate([{
            $group: {
                    _id: null,
                    avg_price: {
                        $avg: "$unit_price"
                    },
                    unit_price: { 
                       "$addToSet": "$unit_price"
                    }
            },
        },{
            $project: {
                avg_price: "$avg_price",
                unit_price: {
                    $filter: {
                        input: "$unit_price",
                        as: "unit_prices",
                        cond: {
                            $lt: ["$$unit_prices", "$avg_price"]
                        }
                    }   
                }
            }
        }
    ])