首页 > 解决方案 > 从 MongoDb 集合中检索前 5 个字段

问题描述

如何从MongoDb数据库集合中检索前 5 个字段?我什至不知道数据库集合的长度。请告诉我从集合中检索前 5 个字段的查询。

这是我在 MERN stack 面试中问我的问题,希望有人能帮助找到答案。

提前致谢。

标签: node.jsmongodbexpress

解决方案


// 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);

推荐阅读