MongoDB find last inserted document

In this MongoDB tutorial, we will learn how to find the last inserted document in MongoDB. These are some of the topics that we are going to cover in this tutorial:

  • MongoDB find last inserted document query
  • MongoDB find last inserted document id
  • MongoDB compass get last inserted document
  • MongoDB find last inserted document using ubuntu
  • MongoDB get last inserted document using python

MongoDB find last inserted document query

When we have a large dataset and we want to find the last inserted document of the collection. For that, we will use two methods of MongoDB to find the last document:

1. sort(): This method is used to sort the document. In this, we have to specify a document containing a list of fields with their sorting order. We will use either 1 or -1 for sorting order in ascending or descending order respectively.

2. limit(): This method is used to limit the number of records or documents the cursor will return.

Syntax:

db.collection_name.find().sort({_id:-1}).limit(1)

Here, the sort() method sort the documents in descending order as per the id field. The limit(1) will limit the document and display only 1 document. Let us understand with the help of an example.

Example:

The following documents were inserted into the last_inserted collection.

db.last_inserted.insertMany([
       {"Name":"John", "Age": 22},
       {"Name":"Bob", "Age": 21},
       {"Name":"Christ", "Age": 26},
       {"Name":"Robert", "Age": 23}
])

Now, you have to apply the below query to find the last inserted document.

db.last_inserted.find().sort({_id:-1}).limit(1)

Here, the sort() method is used to return the documents in descending order as per the id field and the limit(1) method is used to only return one document.

MongoDB find last inserted document query
MongoDB find last inserted document query

Note that, the reason for doing the documents in descending order is so that the last document comes in the first place. After that, we can easily retrieve the document.

Also, check: MongoDB two-phase commit

MongoDB find last inserted document id

In this topic, we will learn to find the id of the last document from the collection. Let us understand with the help of an example.

Example:

The following documents were inserted into the find_id collection.

db.find_id.insertMany([
    {"_id":101,"UserName":"Larry","UserAge":21},
    {"_id":102,"UserName":"Mike","UserAge":26},
    {"_id":103,"UserName":"Chris","UserAge":24},
    {"_id":104,"UserName":"Robert","UserAge":23},
    {"_id":105,"UserName":"John","UserAge":27}
])

After that, we will apply the below query to the find_id collection to find the id of the last document.

db.find_id.find({ }, {"_id": 1}).sort({_id:-1}).limit(1)

Here, the parameter of the find() method will return a single property id. And, the sort() method is used to return the documents in descending order as per the id field and the limit(1) method only return one document.

MongoDB find last inserted document id
MongoDB find last inserted document id

We successfully returned the last inserted document id from the collection.

Read: MongoDB find multiple conditions

MongoDB compass get last inserted document

In this topic, we will learn to get the last inserted document from the collection using MongoDB compass. Let us understand with the help of an example.

Example:

In this example, we will use an existing database and collection and find the last document of the collection. Remember, You have to follow each step without any drop to understand the example.

  • Open the MongoDB compass and connet to the server.
  • Select the existing database and collection where you want to get the last element of the document.
  • You can also create the new database and collection.
  • Here, we are using the demo collection of the test database.
MongoDB compass get last inserted document
Select the database and collection
  • Click on the Aggregation option right side of the Documents option.
  • Here we will apply the aggregation operation to all the documents to get the last document.
  • And, we will use two aggregation operators $sort and $limit for that.
MongoDB compass find the last inserted document
MongoDB compass get last inserted document

Here, the use of the $sort operator is to return the documents in descending order and the $limit operator is used to return a particular number of documents.

  • We have successfully returned the last document of the collection.

Note that, there are many other ways as well to find the last document of the collection but this way you can easily find the last document when you have a large dataset.

Read: MongoDB Update Documents

MongoDB find last inserted document using ubuntu

In this topic, we will learn to find the last inserted document using the ubuntu operating system. Let us understand with the help of an example.

Example:

In ubuntu, we are using the latest version of MongoDB v5.0.3. First of all, we will start the MongoDB server using the below command.

# Start the MongoDB server
systemctl start mongod

# Check the status of MongoDB
systemctl start mongod

# Start the MongoDB shell
mongo
MongoDB find last inserted document
MongoDB find last inserted document

The following documents were inserted into the data collection.

db.data.insertMany([
    { "_id": 1, "House": "201 1st street, Canada" },
    { "_id": 2, "House": "301 2nd street, Australia" },
    { "_id": 3, "House": "222 1st street, USA" },
    { "_id": 4, "House": "399 2nd street, UK" }
])

After that, we will apply the below query to find the last inserted document from the data collection.

db.data.find().sort({_id:-1}).limit(1)

Here, the sort() method is used to return the documents in descending order -1 as per the id field and the limit(1) method is used to only return one document of the collection.

MongoDB find last inserted document using ubuntu
MongoDB find last inserted document using ubuntu

We have successfully retrieved the last inserted document using ubuntu.

Read: How to drop a database in MongoDB

MongoDB get last inserted document using python

In this topic, you will learn to get the last inserted document using python. Let us understand with the help of an example.

Example:

In this example, we will use the existing database and collection and find the last inserted document.

import pymongo

myclient = pymongo.MongoClient("mongodb://127.0.0.1:27017")
mydb = myclient["mydatabase"]
mycol = mydb["sales"]

# Return all the documents in descending order
print("All the documents in descending order")
mydoc = mycol.find().sort( "_id", -1 )
for all_doc in mydoc:
  print(all_doc)

# Return first document
print("First document")
mydoc_1 = mycol.find().sort( "_id", -1 ).limit(1)
for first_doc in mydoc_1:
  print(first_doc)

Here, we have imported the pymongo library to use MongoDB in python. After that, use the MongoClient class of the pymongo library to make the connection with the server.

After that, we have used the existing mydatabase database and sales collection. And, we have used two methods sort() and limit().

The sort() method is used to return the documents in descending order and the limit() method is used to limit the number of records or documents.

Note that, the reason for doing the documents in descending order is so that the last document comes in the first place. After that, we can easily retrieve the document.

Here is the Output of the following given code:

MongoDB get last inserted document using python
MongoDB get last inserted document using python

We have successfully retrieved the last inserted document of the collection using python.

You may also like to read the following MongoDB articles.

So, in this tutorial, we have learned how to find the last inserted document in the MongoDB database. And we have also discussed the following list of topics.

  • MongoDB find last inserted document query
  • MongoDB find last inserted document id
  • MongoDB compass get last inserted document
  • MongoDB find last inserted document using ubuntu
  • MongoDB get last inserted document using python