Mongoose not returning only selected field when running query on collection instead of mongoose model

Viewed 31

I am running same query with mongoose on nodejs and directly on mongo shell. But same query is giving different outputs. I am not sure if I am making some mistake in moongose query. Query1 is run with mongoose and Query2 is run directly on mongo shell.

Query1:

await connection.db.collection("collectionName").find({ updatedAt: { $gt: lastUpdated } }, { _id: 1 }).toArray();

This is giving me all the fields in the documents based on my query while I was expecting it to return only _id field for each document.Here I want only _id field for each document in result.

Query2:

db.find({ updatedAt: { $gt:ISODate('2022-06-20T15:59:09.742+00:00') } }, { _id: 1 })

This is giving me correct output with only _id field for each document.

1 Answers

Need to update query1 like this and it should work fine:

await connection.db.collection("collectionName")
                   .find({ updatedAt: { $gt: lastUpdated } }, {projection:{ _id: 1 }})
                   .toArray();
Related