有沒有辦法限制某個 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" }
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP