简体   繁体   中英

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!!!.

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"]
                    }
                }   
            }
        }
    }
])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM