MongoDB 聚合 $lookup 对具有附加字段的对象数组

编程入门 行业动态 更新时间:2024-10-28 15:22:08
本文介绍了MongoDB 聚合 $lookup 对具有附加字段的对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有两个不同的集合(下面的例子)方法 &项目.至于现在,我对 $lookup 使用 pre 3.6 vanilla 聚合查询:

I have two different collections (example below) methods & items. As for now, I'm using pre 3.6 vanilla aggregation query for $lookup:

MongoPlayground 示例

{ $lookup: { from: "items", localField: "reagents._id", foreignField: "_id", as: "reagent_items" } }

问题是,如果我使用它,我会在 $lookup 阶段错过 quantity 字段(来自 methods.reagents 嵌入)原始集合.现在,我在 lookup 之后立即返回 quantity 但据我所知,Mongo 从 3.6 引入了一种用于 lookup 查询的新语法,所以问题是:

The problem is that if I am using it, I miss quantity field (from methods.reagents embedded) during $lookup stage from original collection. For now, I return quantity right after lookup but as I heard, Mongo introduced from 3.6 a new syntax for lookup queries, so the question is:

能否解决我收到以下结果的问题:

Can it solve my problem for receiving the following results:

{ "_id": 1, "name": "Test", "reagent_items": [ // <= the exact schema of what I need after lookup { "_id": 1, "name": "ItemOne", "other": "field", "quantity": 2 //quantity field from original {array of objects} after lookup }, { "_id": 2, "name": "ItemTwo", "other": "field", "quantity": 4 //quantity field from original {array of objects} after lookup } ], "reagents": [ //original reagents field here just for example, we could remove it { "_id": 1, "quantity": 2 }, { "_id": 2, "quantity": 4 } ] }

方法

{ "_id": 1, "name": "Test", "reagents": [ { _id: 1, quantity: 2 }, { _id: 2, quantity: 4 } ] }

项目

{ "_id": 1, "name": "ItemOne", "other": "field" }, { "_id": 2, "name": "ItemTwo", "other": "field" }

推荐答案

使用 $map 和 $arrayElemAt 为每个 reagent_items 找到对应的 reagent 并应用 $mergeObjects 获取一个对象:

Use $map along with $arrayElemAt to find corresponding reagent for each reagent_items and the apply $mergeObjects to get one object:

db.methods.aggregate([ { $lookup: { from: "items", localField: "reagents._id", foreignField: "_id", as: "reagent_items" } }, { $project: { _id:1, name: 1, reagents: 1, reagent_items: { $map: { input: "$reagent_items", as: "ri", in: { $mergeObjects: [ "$$ri", { $arrayElemAt: [ { $filter: { input: "$reagents", cond: { $eq: [ "$$this._id", "$$ri._id" ] } } }, 0 ] } ] } } } } } ])

蒙戈游乐场

更多推荐

MongoDB 聚合 $lookup 对具有附加字段的对象数组

本文发布于:2023-11-22 10:02:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1616979.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   字段   对象   MongoDB   lookup

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!