MongoDB Node.js 客户端投影

MongoDB Node.js client projection

我知道这可能是一个显而易见的问题,但我是 Mongo 的新手,在查看文档和示例时找不到我做错了什么...我正在尝试查询列表mongo 中的记录从每条记录中提取了一个特定的字段值,我目前有。

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)
});

但是打印出来了

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

而不是

[ {Name: 'TestBook'} ]

我认为您需要在选项参数中提供 projection 以仅获取字段 name:

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

其实find有2个参数,第一个是查询的条件,第二个是一些选项。您可以在此处查看选项支持的字段:http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#find

更新:mongodb 包版本 < 3.0。使用 fields 而不是 projectionbooks.find({}, { fields: { Name:1 }})