如何识别 MongoDB find() 结果集中的最后一条文档?
要识别 MongoDB find() 结果集中的最后一条文档,可以使用按降序排序的 sort() 函数。语法如下 −
db.yourCollectionName.find().sort( { _id : -1 } ).limit(1).pretty();
为了理解上述语法,我们创建一个文档集合。创建带有文档的集合的查询如下 −
> db.identifyLastDocuementDemo.insertOne({"UserName":"Larry","UserAge":24,"UserCountryName":"US"}); { "acknowledged" : true, "insertedId" : ObjectId("5c94a2ff4cf1f7a64fa4df57") } > db.identifyLastDocuementDemo.insertOne({"UserName":"Chris","UserAge":21,"UserCountryName":"UK"}); { "acknowledged" : true, "insertedId" : ObjectId("5c94a3094cf1f7a64fa4df58") } > db.identifyLastDocuementDemo.insertOne({"UserName":"David","UserAge":25,"UserCountryName":"AUS"}); { "acknowledged" : true, "insertedId" : ObjectId("5c94a3174cf1f7a64fa4df59") } > db.identifyLastDocuementDemo.insertOne({"UserName":"Sam","UserAge":26,"UserCountryName":"US"}); { "acknowledged" : true, "insertedId" : ObjectId("5c94a3224cf1f7a64fa4df5a") } > db.identifyLastDocuementDemo.insertOne({"UserName":"Mike","UserAge":27,"UserCountryName":"AUS"}); { "acknowledged" : true, "insertedId" : ObjectId("5c94a32e4cf1f7a64fa4df5b") } > db.identifyLastDocuementDemo.insertOne({"UserName":"Carol","UserAge":28,"UserCountryName":"UK"}); { "acknowledged" : true, "insertedId" : ObjectId("5c94a33c4cf1f7a64fa4df5c") }
使用 find() 方法显示集合中的所有文档。查询如下 −
> db.identifyLastDocuementDemo.find().pretty();
输出如下 −
{ "_id" : ObjectId("5c94a2ff4cf1f7a64fa4df57"), "UserName" : "Larry", "UserAge" : 24, "UserCountryName" : "US" } { "_id" : ObjectId("5c94a3094cf1f7a64fa4df58"), "UserName" : "Chris", "UserAge" : 21, "UserCountryName" : "UK" } { "_id" : ObjectId("5c94a3174cf1f7a64fa4df59"), "UserName" : "David", "UserAge" : 25, "UserCountryName" : "AUS" } { "_id" : ObjectId("5c94a3224cf1f7a64fa4df5a"), "UserName" : "Sam", "UserAge" : 26, "UserCountryName" : "US" } { "_id" : ObjectId("5c94a32e4cf1f7a64fa4df5b"), "UserName" : "Mike", "UserAge" : 27, "UserCountryName" : "AUS" } { "_id" : ObjectId("5c94a33c4cf1f7a64fa4df5c"), "UserName" : "Carol", "UserAge" : 28, "UserCountryName" : "UK" }
以下是识别 MongoDB find() 结果集中最后一条文档的查询 −
> db.identifyLastDocuementDemo.find().sort( { _id : -1 } ).limit(1).pretty();
输出如下 −
{ "_id" : ObjectId("5c94a33c4cf1f7a64fa4df5c"), "UserName" : "Carol", "UserAge" : 28, "UserCountryName" : "UK" }
广告