在请求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
}
编辑
我想提出一个字段的请求问题和answerList和类型。逻辑上,只返回子文档。问题是:如果某些文档有父文档,我只想要父文档,如果文档没有父文档,我想返回这个文档。我不知道该怎么做请帮帮我
我的基本要求
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;
});
新请求(thx @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);
}))
问题:
填充我的结果吗?
(预先多谢!)
亚历克斯
发布于 2020-10-31 01:12:45
您应该将数据分成“问题”和“回答”两个集合,并使用$lookup聚合管道。
尽管如此,如果你真的想要这样的话,你可以试试下面的管道。注意,$unwind确保每个结果只有一个父级。如果您有多个具有相同id的父母,您将得到多个独立的结果。如果您想要一个包含所有父级的数组,那么删除$unwind。
const result = await MyModel.aggregate([
{
$match: {
$or: [
{ question: { $regex: 'Byebye', $options: 'i' } },
{
answerList: {
$elemMatch: { answer: { $regex: 'Byebye', $options: 'i' } },
},
},
],
},
},
{
$lookup: {
from: 'questions',
localField: 'parentId',
foreignField: '_id',
as: 'parent',
},
},
{
$unwind: {
path: '$parent',
preserveNullAndEmptyArrays: true,
},
},
])
https://stackoverflow.com/questions/64617365
复制相似问题