Computer >> Máy Tính >  >> Lập trình >> MongoDB

Làm cách nào để lấy phần tử có id tối đa trong MongoDB?

Để lấy phần tử có id tối đa, bạn có thể sử dụng phương thức find (). Để hiểu khái niệm trên, chúng ta hãy tạo một bộ sưu tập với tài liệu. Truy vấn như sau -

> 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")
}

Hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find (). Truy vấn như sau -

> db.getElementWithMaxIdDemo.find().pretty();

Sau đây là kết quả -

{
   "_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
}

Đây là truy vấn để lấy phần tử có id tối đa -

> db.getElementWithMaxIdDemo.find().sort({_id:-1}).limit(1).pretty()

Sau đây là đầu ra với bản ghi có id tối đa -

{
   "_id" : ObjectId("5c8bbd0880f10143d8431e20"),
   "Name" : "Robert",
   "Age" : 25
}