如何在猫鼬的子文档数组中查找字段?

编程入门 行业动态 更新时间:2024-10-19 06:17:06
本文介绍了如何在猫鼬的子文档数组中查找字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有很多这样的评论对象:

I have an array of review objects like this :

"reviews": { "author": "5e9167c5303a530023bcae42", "rate": 5, "spoiler": false, "content": "This is a comment This is a comment This is a comment.", "createdAt": "2020-04-12T16:08:34.966Z", "updatedAt": "2020-04-12T16:08:34.966Z" },

我想要实现的是查找 author 字段并获取用户数据,但是问题是我尝试使用的查找仅将其返回给我:

What I want to achieve is to lookup the author field and get the user data, but the problem is that the lookup I am trying to use only returns this to me:

代码:

.lookup({ from: 'users', localField: 'reviews.author', foreignField: '_id', as: 'reviews.author', })

响应:

有什么方法可以获取作者在该字段中的数据?那就是作者的ID.

Any way to get the author's data in that field? That's where the author's Id is.

推荐答案

尝试对您的数据库执行以下查询:

Try to execute below query on your database :

db.reviews.aggregate([ /** unwind in general is not needed for `$lookup` for if you wanted to match lookup result with specific elem in array is needed */ { $unwind: { path: "$reviews", preserveNullAndEmptyArrays: true }, }, { $lookup: { from: "users", localField: "reviews.author", foreignField: "_id", as: "author", // Pull lookup result into 'author' field }, }, /** Update 'reviews.author' field in 'reviews' object by checking if 'author' field got a match from 'users' collection. * If Yes - As lookup returns an array get first elem & assign(As there will be only one element returned -uniques), * If No - keep 'reviews.author' as is */ { $addFields: { "reviews.author": { $cond: [ { $ne: ["$author", []] }, { $arrayElemAt: ["$author", 0] }, "$reviews.author", ], }, }, }, /** Group back the documents based on '_id' field & push back all individual 'reviews' objects to 'reviews' array */ { $group: { _id: "$_id", reviews: { $push: "$reviews" }, }, }, ]);

测试: MongoDB-Playground

注意::以防万一,如果文档中还有其他字段需要与reviews一起保留在输出中,则从$group开始使用以下步骤:

Note : Just in case if you've other fields in document along with reviews that needs to be preserved in output then starting at $group use these stages :

{ $group: { _id: "$_id", data: { $first: "$$ROOT" }, reviews: { $push: "$reviews" } } }, { $addFields: { "data.reviews": "$reviews" } }, { $project: { "data.author": 0 } }, { $replaceRoot: { newRoot: "$data" } }

测试: MongoDB-Playground

注意:可能要保持查询在较小的数据集上运行,可能是通过添加$match作为过滤文档的第一阶段来完成的.也有适当的索引.

Note : Try to keep queries to run on lesser datasets maybe by adding $match as first stage to filter documents & also have proper indexes.

更多推荐

如何在猫鼬的子文档数组中查找字段?

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

发布评论

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

>www.elefans.com

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