[英]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.并且我在 Item 集合中插入了记录。 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.我曾尝试使用上面的代码,但我无法弄清楚如何取这个平均值并使用它来检索高于 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"]
}
}
}
}
}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.