MongoDB Node.js客户端投影



我知道这可能是一个显而易见的问题,但我是 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 }})

最新更新