[英]MongoDb: Retrieve all documents higher than the average value of a column
我使用这段代码创建了一个集合。
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"
})
并且我在 Item 集合中插入了记录。 现在我想列出“单价”低于所有商品平均价格的商品。 我试过的是
db.item.aggregate([{
$group: {
_id: null,
averageUnitPrice: {
$avg: "$unit_price"
}
}
}])
我曾尝试使用上面的代码,但我无法弄清楚如何取这个平均值并使用它来检索高于 averageUnitPrice 的文档。 非常感谢任何帮助。! 非常感谢!
所以我终于想通了。 此查询将给我平均值和小于平均值的项目列表。
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.