您正确地认为驱动程序将其错误地解释为
batchSize选项,而忽略了projection语句。
尽管在现代驱动程序版本中,执行此 *** 作的正确方法是实际使用
.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()
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)