简体   繁体   中英

MongoDB find() and retrieve only a field of all documents

Why does opening this API/test page log the whole documents inside Users collection instead of only names?

import { connectToDatabase } from "../../utils/mongodb"

export default async (req, res) => {
  const { db } = await connectToDatabase();

  try{
    const userNames = await db.collection('Users').find({}, {name: 1, _id: 0}).toArray()
    
    console.log('userNames '+JSON.stringify(userNames))

  }catch(err){
    console.log(err)
  }
}

It seems you're using mongodb v3. While the syntax you used above worked in v2, v3 no longer supports the fields parameter. You either need to pass the projection property in on the options object or include a projection document to specify or restrict fields to return, like .project({ name: 1, _id: 0 }) .

const userNames = await db.collection('Users')
  .find({})
  .project({ name: 1, _id: 0 })
  .toArray()

// OR

const userNames = await db.collection('Users')
  .find(
    {}, 
    { projection: { name: 1, _id: 0 } }
   )
  .toArray()

More changes in MongoDB v3: https://github.com/mongodb/node-mongodb-native/blob/master/CHANGES_3.0.0.md

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