Vous avez raison : le pilote interprète à tort ce nom comme l'option batchSize et abandonne l'instruction de projection.
La correction recommandée dans les versions récentes du pilote est d'utiliser la méthode de curseur .project() à la place. Cela reste cohérent avec les pilotes des autres langages.
db.collection('collection').find()
.project({ name: 1, batchSize: 1})
.toArray();
Voici une démonstration complète :
const mongodb = require('mongodb'),
MongoClient = mongodb.MongoClient;
(async function() {
let db;
try {
db = await MongoClient.connect('mongodb://localhost/test');
// Nouvelle forme : .project() comme méthode de curseur
let result = await db.collection('collection').find()
.project({ name: 1, batchSize: 1})
.toArray();
console.log(JSON.stringify(result, undefined, 2));
// Forme héritée : confondue avec une "option de curseur"
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()
}
})()
Produit la sortie suivante :
[
{ "_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": [] }
]
La première sortie est la bonne : elle utilise .project() et renvoie réellement le champ batchSize du document.