有没有一种方法可以限制某个MongoDB集合中的记录数?
是的,您可以将上限参数与上限参数一起使用。以下是语法-
db.createCollection("yourCollectionName",{capped:true,size:yourSizeInBytes,max:howManyRecordsYouWant})
让我们首先创建一个带有capped:true的集合:
> db.createCollection("limitTheNumberOfRecordsDemo",{capped:true,size:200024,max:3}) { "ok" : 1 }
我们现在将创建包含文档的集合-
> db.limitTheNumberOfRecordsDemo.insertOne({"ClientName":"James Brown"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd9e601b50a6c6dd317adad") } > db.limitTheNumberOfRecordsDemo.insertOne({"ClientName":"Sam Williams"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd9e60bb50a6c6dd317adae") } > db.limitTheNumberOfRecordsDemo.insertOne({"ClientName":"David Miller"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd9e612b50a6c6dd317adaf") } > db.limitTheNumberOfRecordsDemo.insertOne({"ClientName":"Carol Taylor"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd9e61ab50a6c6dd317adb0") } > db.limitTheNumberOfRecordsDemo.insertOne({"ClientName":"Adam Smith"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd9e649b50a6c6dd317adb1") } > db.limitTheNumberOfRecordsDemo.insertOne({"ClientName":"John Doe"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd9e64fb50a6c6dd317adb2") }
以下是在find()
method的帮助下显示集合中所有文档的查询。在这里,您从上述集合中仅获得3条记录,因为我们将上限设置为:
> db.limitTheNumberOfRecordsDemo.find();
这将产生以下输出-
{ "_id" : ObjectId("5cd9e61ab50a6c6dd317adb0"), "ClientName" : "Carol Taylor" } { "_id" : ObjectId("5cd9e649b50a6c6dd317adb1"), "ClientName" : "Adam Smith" } { "_id" : ObjectId("5cd9e64fb50a6c6dd317adb2"), "ClientName" : "John Doe" }