Retrieve first 5 fields from MongoDb collection

Viewed 144

How to retrieve first 5 fields from MongoDb database collection? I even don't know the length of a database collection. Please tell me the query for retrieving first 5 fields from collection.

This was the question asked me in my MERN stack interview, hope someone will help to find answer for this.

Thanks in advance.

1 Answers
// Define an empty query document.
const query = {};
// Sort in descending (-1) order by length.
const sort = { length: -1 };
const limit = 5;
const cursor = collection.find(query).sort(sort).limit(limit);
await cursor.forEach(console.dir);
Related