Node.js - MongoDB Limit



MongoDB 中的 Limit() 方法与 SQL 中的 Limit 子句具有类似的效果。它将 find() 查询返回的文档数量限制为指定数量。limit() 方法将单个整数作为参数。如果省略了参数,则意味着没有应用任何限制。

为了理解 limit() 函数的工作原理,我们将使用数据库中的 orders 集合。在可用文档中,价格大于或等于 10 的文档可以通过以下代码检索 -


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

async function main(){

	 	const uri = "mongodb://localhost:27017/";
	 	const client = new MongoClient(uri);

	 	try {
	 	 	 await client.connect();
	 	 	 await limitdocs(client, "mydb", "orders");
	 	} finally {
	 	 	 await client.close();
	 	}
}

main().catch(console.error);


async function limitdocs(client, dbname, colname){
	 	var myqry = {numPurchased:{$gte:10}};
	 	const result = await client.db(dbname).collection(colname).find({"numPurchased":{$gte:10}}).toArray();
	 	console.log(JSON.stringify(result));
}

输出

[{"_id":"658d7f3b30a92c8e5018a43a","orderId":201,"custid":301,"prodId":100,"numPurchased":20},
{"_id":"658d7f3b30a92c8e5018a43b","orderId":202,"custid":302,"prodId":101,"numPurchased":10},
{"_id":"658d7f3b30a92c8e5018a43d","orderId":204,"custid":303,"prodId":103,"numPurchased":15},
{"_id":"658d7f3b30a92c8e5018a43e","orderId":205,"custid":303,"prodId":103,"numPurchased":20},
{"_id":"658d7f3b30a92c8e5018a441","orderId":208,"custid":301,"prodId":100,"numPurchased":10},
{"_id":"658d7f3b30a92c8e5018a442","orderId":209,"custid":303,"prodId":103,"numPurchased":30}]

现在我们将对 find() 查询返回的结果应用限制为 1。limit()方法的语法如下 -


 collection.find(query).limit(number);

将 limitdocs() 函数更改为以下代码,以获取限制为指定数量的文档数量。


async function limitdocs(client, dbname, colname){
	 	var myqry = {numPurchased:{$gte:10}};
	 	const result = await client.db(dbname).collection(colname).find({"numPurchased":{$gte:10}}).limit(1).toArray();
	 	console.log(JSON.stringify(result));
}

输出

[{"_id":"658d7f3b30a92c8e5018a43a","orderId":201,"custid":301,"prodId":100,"numPurchased":20}]

find() 查询从第一次出现开始,在满足过滤条件的情况下获取文档。如果要跳过一定数量的文档,请使用 skip() 子句。


 collection.find(query).limit(x).skip(y)

在 find() 返回的文档中,只有 x 个文档会填充结果集,其中前 y 个文档将被删除。

以下 limitdocs() 函数返回 orders 集合中第二个具有 price>=10 的文档


async function limitdocs(client, dbname, colname){
	 	var myqry = {numPurchased:{$gte:10}};
	 	const result = await client.db(dbname).collection(colname).find({"numPurchased":{$gte:10}}).limit(1).skip(1).toArray();
	 	console.log(JSON.stringify(result));
}

输出


[{"_id":"658d7f3b30a92c8e5018a43b","orderId":202,"custid":302,"prodId":101,"numPurchased":10}]