Search code examples
node.jsmongodbprojection

MongoDB Node.js client projection


I know this is probably an obvious question, but I am new to Mongo, and cannot find what I am doing wrong in looking through the documentation and examples... I am trying to query a list of records in mongo pulling out a specific field value from each of them, and I currently have.

const express = require('express');
const MongoClient = require('mongodb').MongoClient;

// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'TestDB';
let db = null;
let books = null;


// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
  if (err) {
    console.error("Connection Failed")
  }
  db = client.db(dbName);
  books = db.collection('books')
  books.find( {}, { Name:1 } ).toArray().then(console.log)
});

But it prints out

[ { _id: 5b5fae79252d63309c908522,
    Name: 'TestBook',
    chapters: { '1': [Object] } } ]

Instead of

[ {Name: 'TestBook'} ]

Solution

  • I think you need to provide projection in the options parameter to get only the field name:

    books.find({}, { projection: { Name:1 }})
         .toArray()
         .then(console.log)
    

    Actually, find takes 2 parameters, the first one is the criteria for query and the second one includes some options. You can check the supported fields for options here: http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#find

    Updated: For mongodb package version < 3.0. Use fields instead of projection: books.find({}, { fields: { Name:1 }})