我有student
系列
{
_id: 1,
name: "Student",
tasks: [{ month: 1, year: 2018 }]
}
我需要一个只返回任务数组的查询:
db.collection('students').find(
{
'tasks.month': 1,
'tasks.year': 2018
},
{
'tasks.$' : 1
}
).toArray((err, res) => {
console.log(res)
})
这将返回包含所有字段的所有文档,包括name
等等...
find
将返回cursor
。基于cursor
documentation如果你想要project
那么你可以简单地做:
.project({'tasks' : 1})
在你的.toArray
之前...所以你最终得到:
var result = db.collection('students').find({
'tasks.month': 1,
'tasks.year': 2018
}).project({
'tasks': 1
}).toArray((err, res) => {
console.log(res)
})