限制MongoDB中集合中的文档数量?
要限制集合中文档的数量,请设置capped−true。自行设置尺寸。让我们创建一个包含文档的集合-
> db.createCollection( "demo683", { capped: true, size: 5 ,max:4} ) { "ok" : 1 } > db.demo683.insertOne({Value:100}); { "acknowledged" : true, "insertedId" : ObjectId("5ea468afa7e81adc6a0b394e") } > db.demo683.insertOne({Value:500}); { "acknowledged" : true, "insertedId" : ObjectId("5ea468b0a7e81adc6a0b394f") } > db.demo683.insertOne({Value:1000}); { "acknowledged" : true, "insertedId" : ObjectId("5ea468b1a7e81adc6a0b3950") } > db.demo683.insertOne({Value:400}); { "acknowledged" : true, "insertedId" : ObjectId("5ea468b2a7e81adc6a0b3951") } > db.demo683.insertOne({Value:800}); { "acknowledged" : true, "insertedId" : ObjectId("5ea468b3a7e81adc6a0b3952") } > db.demo683.insertOne({Value:700}); { "acknowledged" : true, "insertedId" : ObjectId("5ea468b4a7e81adc6a0b3953") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo683.find();
这将产生以下输出-
{ "_id" : ObjectId("5ea468b1a7e81adc6a0b3950"), "Value" : 1000 } { "_id" : ObjectId("5ea468b2a7e81adc6a0b3951"), "Value" : 400 } { "_id" : ObjectId("5ea468b3a7e81adc6a0b3952"), "Value" : 800 } { "_id" : ObjectId("5ea468b4a7e81adc6a0b3953"), "Value" : 700 }