我对请求 mongoDb 有点头疼。我得到了一个包含文档的集合,这些文档可以在同一个集合中有一个父文档。这是我的收藏。
家长文件
{
"_id": {"$oid": "5f9cac3598361b3370ea47c6"},
"title": "My Title",
"type":1,
"question": "",
"answerList": [],
"__v": 0
}
孩子 1
{
"_id": {"$oid": "5f9cac3598361b3370ea47c7"},
"title": "My Title",
"type":1,
"question": "Q1 ?",
"answerList": [
{
"_id": {"$oid": "5f9cac3598361b3370ea47c9"},
"answer": "Hello1",
},
{
"_id": {"$oid": "5f9cac3598361b3370ea47c8"},
"answer": "Hello2",
}],
"parentId": {"$oid": "5f9cac3598361b3370ea47c6"},
"__v": 0
}
孩子 2
{
"_id": {"$oid": "5f9cac3598361b3370ea47ca"},
"title": "My Title",
"type":1,
"question": "Q2",
"answerList": [
{
"_id": {"$oid": "5f9cac3598361b3370ea47cc"},
"answer": "Byebye1"
},
{
"_id": {"$oid": "5f9cac3598361b3370ea47cb"},
"answer": "Byebye2",
}],
"feedType": "SURVEY",
"parentId": {"$oid": "5f9cac3598361b3370ea47c6"},
"__v": 0
}
编辑
我想通过字段question和answerList和type提出请求。逻辑上只返回子文档。问题是:如果某些文档有父文档,我只想要父文档,如果文档没有父文档,我想返回此文档。我不知道该怎么做请帮助我
我的基本要求
var polls = MyModel.find({
$and: [
{ confidentiality: ConfidentialityEnum.PUBLIC },
{
$or: [
{ question: { $regex: fields.query, $options: "i" } },
{
answerList: {
$elemMatch: { answer: { $regex: fields.query, $options: "i" } },
},
},
],
},
],
})
.populate("createdBy", ["firstName", "lastName", "avatar"])
.select("+voteList")
.populate("voteList.user", ["_id", "avatar"])
.select("+commentList")
.populate("commentList.user", "_id")
.then((data) => {
return data;
});
新请求(谢谢@Brmm)
const result = MyModel.aggregate([
{
$match: {
$and: [
{ confidentiality: ConfidentialityEnum.PUBLIC },
{
$or: [
{ question: { $regex: fields.query, $options: 'i' } },
{
answerList: {
$elemMatch: { answer: { $regex: fields.query, $options: 'i' } },
},
},
],
}
]
},
},
{
$lookup: {
from: 'questions',
localField: 'parentId',
foreignField: '_id',
as: 'parent',
},
},
{
$unwind: {
path: '$parent',
preserveNullAndEmptyArrays: true,
},
},
]).then((data => {
console.log(data);
}))
问题 :
在 console.log 中,我得到了有父文档而不是只有父文档的文档。
是否可以使用 MyModel.aggregate 填充我的结果?
先感谢您 !:)
亚历克斯