如何在隐藏某些字段的情况下发布数组中的某些元素?
How to publish certain element in array with some fields hidden?
我有这个测验文件:
{
_id: 001,
quiz: "cartoon familes",
questions:[
{
_id: 100,
question: "who is the eldest ?",
order: 1,
answers: [
{ _id: 101, answer: "Bart Simpson", points: 100 },
{ _id: 102, answer: "Lisa Simpson", points: 0 },
{ _id: 103, answer: "Maggie Simpson", points: 0 }
]
},
{
_id: 200,
question: "who is the eldest ?",
order: 2,
answers: [
{ _id: 201, answer: "Chris Griffin", points: 0 },
{ _id: 202, answer: "Meg Griffin", points: 100 },
{ _id: 203, answer: "Stewie Griffin", points: 0 }
]
}
]
}
我只想获取具有字段 order: 1
的问题(所有其他问题都将被隐藏)并且我还希望隐藏 points
字段。
我该怎么做?
您可以通过聚合查询中的两个 $project
阶段实现此目的,如下所示:
db.collection.aggregate([
{
$project:{
questions:{
$filter:{
input:"$questions",
as:"qu",
cond:{
$eq:[
"$$qu.order",
1
]
}
}
}
}
},
{
$project:{
"questions.answers.points":0
}
}
])
这个输出:
{
"_id" : 1,
"questions" : [
{
"_id" : 100,
"question" : "who is the eldest ?",
"order" : 1,
"answers" : [
{
"_id" : 101,
"answer" : "Bart Simpson"
},
{
"_id" : 102,
"answer" : "Lisa Simpson"
},
{
"_id" : 103,
"answer" : "Maggie Simpson"
}
]
}
]
}
我有这个测验文件:
{
_id: 001,
quiz: "cartoon familes",
questions:[
{
_id: 100,
question: "who is the eldest ?",
order: 1,
answers: [
{ _id: 101, answer: "Bart Simpson", points: 100 },
{ _id: 102, answer: "Lisa Simpson", points: 0 },
{ _id: 103, answer: "Maggie Simpson", points: 0 }
]
},
{
_id: 200,
question: "who is the eldest ?",
order: 2,
answers: [
{ _id: 201, answer: "Chris Griffin", points: 0 },
{ _id: 202, answer: "Meg Griffin", points: 100 },
{ _id: 203, answer: "Stewie Griffin", points: 0 }
]
}
]
}
我只想获取具有字段 order: 1
的问题(所有其他问题都将被隐藏)并且我还希望隐藏 points
字段。
我该怎么做?
您可以通过聚合查询中的两个 $project
阶段实现此目的,如下所示:
db.collection.aggregate([
{
$project:{
questions:{
$filter:{
input:"$questions",
as:"qu",
cond:{
$eq:[
"$$qu.order",
1
]
}
}
}
}
},
{
$project:{
"questions.answers.points":0
}
}
])
这个输出:
{
"_id" : 1,
"questions" : [
{
"_id" : 100,
"question" : "who is the eldest ?",
"order" : 1,
"answers" : [
{
"_id" : 101,
"answer" : "Bart Simpson"
},
{
"_id" : 102,
"answer" : "Lisa Simpson"
},
{
"_id" : 103,
"answer" : "Maggie Simpson"
}
]
}
]
}