database - mongodb array aggregation extract to parent
问题描述
I am trying to get first date from inner array in mongodb object and add it to it's parent with aggregation. Example:
car: {
"model": "Astra",
"productions": [
"modelOne": {
"dateOfCreation": "2019-09-30T10:15:25.026+00:00",
"dateOfEstimation": "2017-09-30T10:15:25.026+00:00",
"someOnterInfo": "whatever"
},
"modelTwo": {
"dateOfCreation": "2017-09-30T10:15:25.026+00:00",
"dateOfEstimation": "2019-09-30T10:15:25.026+00:00",
"someOnterInfo": "whatever"
}
]
}
to be turned in
car: {
"model": "Astra",
"earliestDateOfEstimation": "2017-09-30T10:15:25.026+00:00",
"earliestDateOfCreation": "2017-09-30T10:15:25.026+00:00"
}
How can I achieve that?
解决方案
I'm assuming that modelOne
and modelTwo
are unknown when you start your aggregation. The key step is to run $map along with $objectToArray in order to get rid of those two values. Then you can just use $min to get "earliest" values:
db.collection.aggregate([
{
$addFields: {
dates: {
$map: {
input: "$car.productions",
in: {
$let: {
vars: { model: { $arrayElemAt: [ { $objectToArray: "$$this" }, 0 ] } },
in: "$$model.v"
}
}
}
}
}
},
{
$project: {
_id: 1,
"car.model": 1,
"car.earliestDateOfEstimation": { $min: "$dates.dateOfEstimation" },
"car.earliestDateOfCreation": { $min: "$dates.dateOfCreation" },
}
}
])
EDIT:
First step can be simplified if there's always modelOne
, 'modelTwo'... (fixed number)
db.collection.aggregate([
{
$addFields: {
dates: { $concatArrays: [ "$car.productions.modelOne", "$car.productions.modelTwo" ] }
}
},
{
$project: {
_id: 1,
"car.model": 1,
"car.earliestDateOfEstimation": { $min: "$dates.dateOfEstimation" },
"car.earliestDateOfCreation": { $min: "$dates.dateOfCreation" },
}
}
])
推荐阅读
- linux - 试图了解“StreamTrans #3”在 Firefox 中的作用?
- sql - PGSQL - 在 WHERE 子句中结合许多 AND + OR
- python - 用可变数量的项目注释元组并且第一项是不同类型的
- c# - ASP.NET Core 3.1 Razor 将字符串转换为日期时间
- dictionary - 从 map[string][]string 返回的空列表有什么特别之处
- python - 在 HTML 中显示 MySQL Blob
- reactjs - Walletconnect 未在移动设备中触发应用程序但重定向
- sql - 使用 R 根据存储在当前变量名称(由“_”分隔)中的唯一信息将数据帧转换为长格式
- python - 追加大型 Pytables HDF5 文件的最快方法
- r - 试图安排两个 gganimate 图会引发错误:magick_image_info(image) 中的错误:rsession.exe:几何参数无效