Mongodb find方法总是返回文档的所有元素

问题描述 投票:0回答:1

我有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等等...

javascript node.js mongodb
1个回答
0
投票

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)
})
© www.soinside.com 2019 - 2024. All rights reserved.