mongodb - MongoDB 查找聚合
问题描述
我有像这样的停车收藏:
parking: {
_id: xxxxxx,
name: xxxxxx,
vehicles: [{vehicleId: xxxxx, bid: xxxxx}...]
}
和汽车收藏:
car: {
_id: "xxxx",
attributes: [xxxxx],
color: "xxxx"
}
当我进行查找聚合时:
$lookup: {
from: "car",
localField: "vehicles.vehicleId",
foreignField: "_id",
as: "cars"
}
我得到:
parking: {
_id: xxxxxx,
name: xxxxxx,
vehicles: [{vehicleId: xxxxx, bid: xxxxx}],
cars: [car1,car2...]
}
因此,我很难将新车阵列与车辆阵列中匹配 id 的对象合并。我可以用匹配的汽车文件以某种方式替换 vehicleId 吗?
我试过这个,但组操作从停车场中删除名称字段
db.parking.aggregate([
{ "$unwind": "$vehicles" },
{ "$lookup": {
"from": "car",
"as": "vehicles.vehicle",
"localField": "vehicles.vehicleId",
"foreignField": "_id"
}},
{ "$unwind": "$vehicles.vehicle" },
{ "$group": {
"_id": "$_id",
"vehicles": { "$push": "$vehicles" }
}}
])
解决方案
$map
通过组合运算符更容易使用运算$reduce
符。
试试这个:
db.parking.aggregate([
{
"$lookup": {
"from": "car",
"localField": "vehicles.vehicleId",
"foreignField": "_id",
"as": "cars"
}
},
{
$addFields: {
vehicles: {
$map: {
input: "$vehicles",
as: "veh",
in: {
bid: "$$veh.bid",
vehicleId: {
$reduce: {
input: "$cars",
initialValue: "$$veh.vehicleId",
in: {
$cond: [
{
$eq: [ "$$this._id", "$$veh.vehicleId" ]
},
"$$this",
"$$value"
]
}
}
}
}
}
},
cars: "$$REMOVE"
}
}
])
推荐阅读
- sql - TSQL:获取每小时的销售数据
- unity3d - Graphics.Blit uv 信息是如何传递的?
- python - TF 中的索引操作
- python - Scrapy 使用 crawlerprocess 运行时抛出错误
- javascript - 为什么 Flow 不支持详尽检查中的常量?
- python - Flask TypeError:“str”和“int”的实例之间不支持“<”
- c - 使用用户定义函数的帕斯卡三角形的替代方法
- google-apps-script - 有没有一种干净的方法可以将稀疏网格写入谷歌表格范围
- rust - 如何获得 tokio::fs::File::open 的静态路径?
- docker - gcloud 集群无法提取 eu.gcr.io 所需的身份验证