有没有办法限制某个 MongoDB 集合中的记录数?
可以,你可以对 capped 参数使用最大值。语法如下 −
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() 方法显示集合中的所有文档。这里你只将从上述集合中获取 3 条记录,因为我们已经设置了上面带最大值的上限 −
> db.limitTheNumberOfRecordsDemo.find();
这样将产生以下输出 −
{ "_id" : ObjectId("5cd9e61ab50a6c6dd317adb0"), "ClientName" : "Carol Taylor" } { "_id" : ObjectId("5cd9e649b50a6c6dd317adb1"), "ClientName" : "Adam Smith" } { "_id" : ObjectId("5cd9e64fb50a6c6dd317adb2"), "ClientName" : "John Doe" }
广告