如何在MongoDB中获取具有最大ID的元素?
要获得具有最大id的元素,可以使用find()
方法。为了理解上述概念,让我们用文档创建一个集合。查询如下-
> db.getElementWithMaxIdDemo.insertOne({"Name":"John","Age":21});{
"acknowledged" : true,
"insertedId" : ObjectId("5c8bbce480f10143d8431e1c")
}
> db.getElementWithMaxIdDemo.insertOne({"Name":"Larry","Age":24});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8bbcec80f10143d8431e1d")
}
> db.getElementWithMaxIdDemo.insertOne({"Name":"David","Age":23});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8bbcf580f10143d8431e1e")
}
> db.getElementWithMaxIdDemo.insertOne({"Name":"Chris","Age":20});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8bbcfe80f10143d8431e1f")
}
> db.getElementWithMaxIdDemo.insertOne({"Name":"Robert","Age":25});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8bbd0880f10143d8431e20")
}
在find()
method的帮助下显示集合中的所有文档。查询如下-
> db.getElementWithMaxIdDemo.find().pretty();
以下是输出-
{"_id" : ObjectId("5c8bbce480f10143d8431e1c"),
"Name" : "John",
"Age" : 21
}
{
"_id" : ObjectId("5c8bbcec80f10143d8431e1d"),
"Name" : "Larry",
"Age" : 24
}
{
"_id" : ObjectId("5c8bbcf580f10143d8431e1e"),
"Name" : "David",
"Age" : 23
}
{
"_id" : ObjectId("5c8bbcfe80f10143d8431e1f"),
"Name" : "Chris",
"Age" : 20
}
{
"_id" : ObjectId("5c8bbd0880f10143d8431e20"),
"Name" : "Robert",
"Age" : 25
}
这是获取具有最大id的元素的查询-
> db.getElementWithMaxIdDemo.find().sort({_id:-1}).limit(1).pretty()
以下是具有最大id的记录的输出-
{"_id" : ObjectId("5c8bbd0880f10143d8431e20"),
"Name" : "Robert",
"Age" : 25
}
以上是 如何在MongoDB中获取具有最大ID的元素? 的全部内容, 来源链接: utcz.com/z/347365.html