Search code examples
node.jsmongodbnode-mongodb-native

Nodejs Mongodb driver: how to combine index hint and projections


Struggling to combine index hints and query projections with the Nodejs driver.

This works if we only include a hint:

db.collection('battle').find({}, {'hint': 'myindex'}).toArray();

This works if we only include a projection:

db.collection('battle').find({}, {'result.replay': 0}).toArray();

but, this ignores the projection:

db.collection('battle').find({}, {'hint': 'myindex', 'result.replay': 0}).toArray();

Solution

  • Seems I had the order incorrect:

    var cursor = collection.find(query, [fields], options);
    

    which means:

    db.collection('battle').find({}, {'result.replay': 0}, {'hint': 'myindex'}).toArray();