• Node.js Video Tutorials

Node.js - MongoDB 限制



MongoDB 中的 `limit()` 方法与 SQL 中的 LIMIT 子句效果类似。它将 `find()` 查询返回的文档数量限制为指定数量。`limit()` 方法接受一个整数作为参数。如果省略参数,则表示未应用限制。

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

示例

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

async function main(){

   const uri = "mongodb://127.0.0.1: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 集合中第二个价格 >= 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}]
广告