MongoDB查询以选择10个最新文档而不更改顺序?
skip()
。在下skip()
,设置“count()–10”以获取10个最新文档。让我们创建一个包含文档的集合-> db.demo500.insertOne({value:10});{ "acknowledged" : true, "insertedId" : ObjectId("5e8749c5987b6e0e9d18f55a") } > db.demo500.insertOne({value:1200});{ "acknowledged" : true, "insertedId" : ObjectId("5e8749c8987b6e0e9d18f55b") } > db.demo500.insertOne({value:19});{ "acknowledged" : true, "insertedId" : ObjectId("5e8749cb987b6e0e9d18f55c") } > db.demo500.insertOne({value:28});{ "acknowledged" : true, "insertedId" : ObjectId("5e8749cf987b6e0e9d18f55d") } > db.demo500.insertOne({value:50});{ "acknowledged" : true, "insertedId" : ObjectId("5e8749d1987b6e0e9d18f55e") } > db.demo500.insertOne({value:70});{ "acknowledged" : true, "insertedId" : ObjectId("5e8749d4987b6e0e9d18f55f") } > db.demo500.insertOne({value:100});{ "acknowledged" : true, "insertedId" : ObjectId("5e8749d7987b6e0e9d18f560") } > db.demo500.insertOne({value:10});{ "acknowledged" : true, "insertedId" : ObjectId("5e8749d9987b6e0e9d18f561") } > db.demo500.insertOne({value:98});{ "acknowledged" : true, "insertedId" : ObjectId("5e8749dc987b6e0e9d18f562") } > db.demo500.insertOne({value:80});{ "acknowledged" : true, "insertedId" : ObjectId("5e8749e0987b6e0e9d18f563") } > db.demo500.insertOne({value:75});{ "acknowledged" : true, "insertedId" : ObjectId("5e874c73987b6e0e9d18f564") } > db.demo500.insertOne({value:68});{ "acknowledged" : true, "insertedId" : ObjectId("5e874c78987b6e0e9d18f565") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo500.find();
这将产生以下输出-
{ "_id" : ObjectId("5e8749c5987b6e0e9d18f55a"), "value" : 10 } { "_id" : ObjectId("5e8749c8987b6e0e9d18f55b"), "value" : 1200 } { "_id" : ObjectId("5e8749cb987b6e0e9d18f55c"), "value" : 19 } { "_id" : ObjectId("5e8749cf987b6e0e9d18f55d"), "value" : 28 } { "_id" : ObjectId("5e8749d1987b6e0e9d18f55e"), "value" : 50 } { "_id" : ObjectId("5e8749d4987b6e0e9d18f55f"), "value" : 70 } { "_id" : ObjectId("5e8749d7987b6e0e9d18f560"), "value" : 100 } { "_id" : ObjectId("5e8749d9987b6e0e9d18f561"), "value" : 10 } { "_id" : ObjectId("5e8749dc987b6e0e9d18f562"), "value" : 98 } { "_id" : ObjectId("5e8749e0987b6e0e9d18f563"), "value" : 80 } { "_id" : ObjectId("5e874c73987b6e0e9d18f564"), "value" : 75 } { "_id" : ObjectId("5e874c78987b6e0e9d18f565"), "value" : 68 }
以下是查询以选择10个最新文档而不更改顺序-
> db.demo500.find().skip(db.demo500.count() - 10);
这将产生以下输出-
{ "_id" : ObjectId("5e8749cb987b6e0e9d18f55c"), "value" : 19 } { "_id" : ObjectId("5e8749cf987b6e0e9d18f55d"), "value" : 28 } { "_id" : ObjectId("5e8749d1987b6e0e9d18f55e"), "value" : 50 } { "_id" : ObjectId("5e8749d4987b6e0e9d18f55f"), "value" : 70 } { "_id" : ObjectId("5e8749d7987b6e0e9d18f560"), "value" : 100 } { "_id" : ObjectId("5e8749d9987b6e0e9d18f561"), "value" : 10 } { "_id" : ObjectId("5e8749dc987b6e0e9d18f562"), "value" : 98 } { "_id" : ObjectId("5e8749e0987b6e0e9d18f563"), "value" : 80 } { "_id" : ObjectId("5e874c73987b6e0e9d18f564"), "value" : 75 } { "_id" : ObjectId("5e874c78987b6e0e9d18f565"), "value" : 68 }