批量字段名称在字段投影中被忽略

我有一个user_batch集合。 它包含以下文件:

[{ _id: ObjectId("594baf96256597ec035df23c"), name: "Batch 1", batchSize: 30, users:[] }, { _id: ObjectId("594baf96256597ec035df234"), name: "Batch 2", batchSize: 50, users:[] }] 

在查找查询我想项目只有名称批处理大小 。 但是当我从nodejs执行查询查询时,我得到查询结果中的整个文档。 查询:

 db.collection('user_batch').find({}, {name: 1, batchSize: 1}).toArray((err, result) => { if(err) console.log(err) else console.log(result) }) 

如果我只是通过{name:1},那么它会投影_id和名称。 但是,如果我传递批量大小,那么它将返回整个文档。

注意:在Mongo Shell中执行此查询时,我没有遇到这个问题

你是正确的,驱动程序错误地将其解释为batchSize选项,并忽略投影语句。

在现代驱动程序发行版中,正确的方法是实际使用.project() “游标方法”。 这更符合其他语言驱动程序的实现。

  db.collection('collection').find() .project({ name: 1, batchSize: 1}) .toArray(); 

作为一个充分的示范:

 const mongodb = require('mongodb'), MongoClient = mongodb.MongoClient; (async function() { let db; try { db = await MongoClient.connect('mongodb://localhost/test'); // New form uses .project() as a cursor method let result = await db.collection('collection').find() .project({ name: 1, batchSize: 1}) .toArray(); console.log(JSON.stringify(result,undefined,2)); // Legacy form confuses this as being a legacy "cursor option" let other = await db.collection('collection') .find({},{ name: 1, batchSize: 1 }) .toArray(); console.log(JSON.stringify(other,undefined,2)); } catch(e) { console.error(e) } finally { db.close() } })() 

产生输出:

 [ { "_id": "594baf96256597ec035df23c", "name": "Batch 1", "batchSize": 30 }, { "_id": "594baf96256597ec035df234", "name": "Batch 2", "batchSize": 50 } ] [ { "_id": "594baf96256597ec035df23c", "name": "Batch 1", "batchSize": 30, "users": [] }, { "_id": "594baf96256597ec035df234", "name": "Batch 2", "batchSize": 50, "users": [] } ] 

如果第一个输出表单是更正的,使用.project()