在集合中查找最后一个对象的 MongoDB 查询?
要查找集合中的最后一个对象,首先使用 sort() 对值进行排序。使用 limit() 来获取值的数量,即,如果你只想要最后一个对象,那么使用 limit(1)。
让我们首先创建一个带有文档的集合 -
> db.demo141.insertOne({"Name":"Chris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e31c347fdf09dd6d08539ae")
}
> db.demo141.insertOne({"Name":"David"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e31c34bfdf09dd6d08539af")
}
> db.demo141.insertOne({"Name":"Bob"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e31c34ffdf09dd6d08539b0")
}
> db.demo141.insertOne({"Name":"Mike"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e31c352fdf09dd6d08539b1")
}使用 find() 方法从集合中显示所有文档 -
> db.demo141.find();
这将产生以下输出 -
{ "_id" : ObjectId("5e31c347fdf09dd6d08539ae"), "Name" : "Chris" }
{ "_id" : ObjectId("5e31c34bfdf09dd6d08539af"), "Name" : "David" }
{ "_id" : ObjectId("5e31c34ffdf09dd6d08539b0"), "Name" : "Bob" }
{ "_id" : ObjectId("5e31c352fdf09dd6d08539b1"), "Name" : "Mike" }以下是在集合中查找最后一个对象的查询 -
> db.demo141.find().sort({_id:-1}).limit(1);这将产生以下输出 -
{ "_id" : ObjectId("5e31c352fdf09dd6d08539b1"), "Name" : "Mike" }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP