mongodb - 使用聚合和查找 mongodb 从对象数组中获取最小值
问题描述
我有两个系列properties
,property_prices
并且关系是一个属性多个价格。所以我试图加入他们,然后从中找到最小值property_prices.monthly_unit_price.unit_price
。所以我可以从整个房产定价中获得房产及其价格和最小单位价格值。
Property Collection
{
"_id": "1",
"status": "Approved",
"name": "My Property Lake"
}
Property Price Collection
其中monthly_unit_price 从一月到十二月有对象
{
"property_prices": [
{
"property_id": "1",
"block_id": "ABC",
"monthly_unit_price": [{ "month": "Jan", "unit_price": 100 }, { "month": "Dec", "unit_price": "1200" }],
},
{
"property_id": "1",
"block_id": "DEF",
"monthly_unit_price": [{ "month": "Jan", "unit_price": "200" }, { "month": "Dec", "unit_price": "2400" }],
}
]
}
基本上我想从 property_prices 获得最小值unit_price
为property_id
1
所以我尝试使用aggregate
,lookup
但我无法从property_prices
. 这是我尝试过的
await Property.aggregate([
{
$lookup: {
from: 'property_prices',
as: 'property_prices',
let: { property_id: '$_id' },
pipeline: [
{
$match: {
$expr: {
$and: [
{ $eq: ['$property_id', '$$property_id'] },
{ $eq: ['$status', 'Completed'] },
]
}
}
},
]
},
},
{
$unwind: "$property_prices"
},
{
$group: {
_id: '$property_prices.property_id',
minInvestment: { "$min": "$property_prices.monthly_unit_price.unit_price" }
}
},
]);
我期待的结果是
{
"_id": "1",
"status": "Approved",
"name": "My Property Lake",
"property_prices": [
{
"property_id": "1",
"block_id": "ABC",
"monthly_unit_price": [{ "month": "Jan", "unit_price": 100 }, { "month": "Dec", "unit_price": "1200" }],
},
{
"property_id": "1",
"block_id": "DEF",
"monthly_unit_price": [{ "month": "Jan", "unit_price": "200" }, { "month": "Dec", "unit_price": "2400" }],
}
],
"minInvestment":100
}
解决方案
您走在正确的轨道上,您只需要“按摩”文档结构一点点,因为它是一个嵌套数组。$map
这是一个使用and运算符的快速示例$reduce
。
请注意,我还必须使用 将值转换为数字类型$toInt
,我建议在更新/插入时处理这些事情。
db.properties.aggregate([
{
$lookup: {
from: "property_prices",
as: "property_prices",
let: {
property_id: "$_id"
},
pipeline: [
{
$match: {
$expr: {
$and: [
{
$eq: [
"$property_id",
"$$property_id"
]
},
{
$eq: [
"$status",
"Completed"
]
}
]
}
}
}
]
}
},
{
$addFields: {
minInvestment: {
$min: {
$reduce: {
input: {
$map: {
input: "$property_prices",
as: "property",
in: {
$map: {
input: "$$property.monthly_unit_price",
as: "price",
in: {
$toInt: "$$price.unit_price"
}
}
}
}
},
initialValue: [],
in: {
"$concatArrays": [
"$$value",
"$$this"
]
}
}
}
}
}
}
])
推荐阅读
- reactjs - 新 SDK (v2) 中的 Cloudinary CORS
- java - 代表由不同部门组成的大学
- websocket - MQTT WebSocket 连接失败
- json - NiFi更新记录escapeJson记录路径不起作用
- authentication - 如何在剧作家中使用 MFA?
- php - PHP 警告:extract() 期望参数 1 是数组
- github - 跨多个 github 存储库管理问题
- laravel - 如何在 laravel 中集成来自 autocad forge 的 BIM 360 API?
- r - 将 RasterLayer 导出为 shapefile(从 R 到 QGIS)
- javascript - 选择多个复选框后如何检查是否有任何值保存在数组中