batchSize field name ignored in Field Projection

You are correct that the driver incorrectly interprets this as the batchSize option and ignores the projection statement.

The correct way to do this though in modern driver releases is to actually use the .project() “cursor method” instead. This is more consistent with other language driver implementations.

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

As a full demonstration:

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

})()

Produces the output:

[
  {
    "_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": []
  }
]

Where the first output form is the corrected one, using .project()

Leave a Comment