要从MongoDBfind()
结果集中识别最后一个文档,可以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()
method的帮助下显示集合中的所有文档。查询如下-
> 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" }
这是从MongoDBfind()
结果集中识别最后一个文档的查询-
> db.identifyLastDocuementDemo.find().sort( { _id : -1 } ).limit(1).pretty();
以下是输出-
{ "_id" : ObjectId("5c94a33c4cf1f7a64fa4df5c"), "UserName" : "Carol", "UserAge" : 28, "UserCountryName" : "UK" }