简体   繁体   中英

Mongodb find method always return all elements of the documents

I have student collection

{
  _id: 1,
  name: "Student",
  tasks: [{ month: 1, year: 2018 }]
}

I need a query which would return only array of tasks:

db.collection('students').find(
  {
    'tasks.month': 1,
    'tasks.year': 2018
  },
  {
    'tasks.$' : 1
  }
).toArray((err, res) => {
  console.log(res)
})

This return all the documents with all field, including name and so on ...

The find would return a cursor . Based on the cursor documentation if you want to project then you can simply do:

.project({'tasks' : 1})

before your .toArray ... so you end up with:

var result = db.collection('students').find({
  'tasks.month': 1,
  'tasks.year': 2018
}).project({
  'tasks': 1
}).toArray((err, res) => {
  console.log(res)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM