MongoDb:检索所有高于某列平均值的文档
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 集合中插入了记录。现在我想列出 "unit_price" 低于所有商品平均价格的商品。
我试过的是
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"]
}
}
}
}
}
])
我已经使用这段代码创建了一个集合。
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 集合中插入了记录。现在我想列出 "unit_price" 低于所有商品平均价格的商品。 我试过的是
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"]
}
}
}
}
}
])