Home > other >  Unable to select specific field for MongoDB find operation
Unable to select specific field for MongoDB find operation

Time:12-24

I am trying to select only one field from a mongo document and print the value for it. I found this answer https://stackoverflow.com/a/25589150 which showed how we can achieve this. Below I have tried doing the same yet the entire document ends up getting printed.

const mongoHost =
  'somemongourl'
const mongodb = require('mongodb');
const { MongoClient } = mongodb;

MongoClient.connect(
  mongoHost,
  { useNewUrlParser: true },
  async (error, client) => {
    if (error) {
      return console.log('Unable to connect to database!');
    }
    const db = client.db('cartDatabase');

    const values = await db
      .collection('cart')
      .find({ customer_key: 'c_1' }, { customer_key: 1, _id: 0 })
      .toArray();

    console.log(values);
  }
);

This is the output for example I got :-

[
  {
    _id: new ObjectId("611b7d1a848f7e6daba69014"),
    customer_key: 'c_1',
    products: [ [Object] ],
    coupon: '',
    discount: 0,
    vat: 0,
    cart_total: 999.5,
    cart_subtotal: 999.5
  }
]

This is what I was expecting -

[
  {
    customer_key: 'c_1'
  }
]

CodePudding user response:

The standard Node.js MongoDB driver requires a top-level projection property for the options parameter if you wish to project your documents. This would result in the second parameter of your find() call looking like this:

{ projection: { customer_key: 1, _id: 0 } }

This is indicated in the Node.js MongoDB driver API documentation, which is notably not a 1-to-1 match with the MongoDB shell API.

As of the time of this answer, you could find the collection.find() reference here. This reference shows the following method signature (again as of when this answer was written):

find(filter: Filter<WithId<TSchema>>, options?: FindOptions<Document>)

Following the FindOptions parameter takes us to this reference page, which details the various top-level options properties available for the find() method. Among these is the projection property in question.

In short, don't use the normal MongoDB documentation as a reference for your programming language's MongoDB driver API. There will often be disconnects between the two.

  • Related