mongodb - 如何$查找/填充数组内的嵌入式文档?
问题描述
如何$查找/填充数组内的嵌入式文档?
下面是我的架构的样子。
const CommentSchema = new mongoose.Schema({
commentText:{
type:String,
required: true
},
arrayOfReplies: [{
replyText:{
type:String,
required: true
},
replier: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
required: true,
}],
}],
});
如何获得如下所示的查询结果:
[
{
commentText: 'comment text',
arrayOfReplies: [
{
replyText: 'replyText',
replier: {
username:"username"
bio: 'bio'
}
}
]
}
]
我正在尝试填充replier
数组中的字段arrayOfReplies
。我已经尝试了以下聚合查询的几种变体。那些已经接近我想要达到的目标有一个缺点。没有回复的评论有一个arrayOfReplies
包含空对象的数组。即arrayOfReplies: [{}]
,本质上意味着数组不为空。
我曾尝试在其他管道运算符中使用add fields、$mergeObjects,但无济于事。
如何 $lookup/populate数组replier
内的文档?arrayOfReplies
下面是我的聚合查询主要部分的模板,减去尝试填充replier
文档。
Comment.aggregate([
{$unwind: {"path": '$arrayOfReplies', "preserveNullAndEmptyArrays": true }},
{$lookup:{from:"users",localField:"$arrayOfReplies.replier",foreignField:"_id",as:"replier"}},
{$unwind: {"path": "$replier", "preserveNullAndEmptyArrays": true }},
{$group: {
_id : '$_id',
commentText:{$first: '$commentText'},
userWhoPostedThisComment:{$first: '$userWhoPostedThisComment'},
arrayOfReplies: {$push: '$arrayOfReplies' },
}},
解决方案
您可以使用以下聚合:
Comment.aggregate([
{
$unwind: {
"path": "$arrayOfReplies",
"preserveNullAndEmptyArrays": true
}
},
{
$lookup: {
from: "users",
localField: "arrayOfReplies.replier",
foreignField: "_id",
as: "replier"
}
},
{
$addFields: {
"arrayOfReplies.replier": {
$arrayElemAt: [
"$replier",
0
]
}
}
},
{
$project: {
"replier": 0
}
},
{
$group: {
_id: "$_id",
"arrayOfReplies": {
"$push": "$arrayOfReplies"
},
commentText: {
"$first": "$commentText"
}
}
}
]);
推荐阅读
- javascript - 注入 DOM 后如何使用 API 处理 Wistia 视频
- javascript - 猫鼬 findOneAndUpdate 为 err 和 doc 返回 null(使用 Jest)
- tfs - 如何查看我在 VSTS 项目中所做的更改?
- php - Laravel CSV 导入 - 我可以使用请求验证吗?
- intellij-idea - 使用 IntelliJ Idea 和 SonarLint 连接到 SonarQube 服务器时出现错误
- php - 一个while循环中有两个查询
- javascript - 如何创建 JSON 对象数组?
- excel - 使用 VBA 在 Outlook 中添加文件作为附件时,如何使打开的文件夹对话框窗口成为活动窗口?
- javascript - 是否可以保存由 javascript 附加的单选按钮?
- zerobrane - Zerobrane:分形样本:zplane.lua 正在退出并出现错误