How to Sort Collection by Order Inserted using the MongoDB Shell

Introduction

It is extremely common to want to your query data to be ordered by when it was inserted. In a lot of situations the most recent data is the most relevant data so this type of query happens frequently in web applications. For example if your web application lists the credit cards that have been used, you’d most likely want to use the most recently added one. The same type of logic would also apply to phone numbers or addresses, so this type of query has lots of real world applications and is good to know how to do. Today we’ll show you how to sor a collection by the order inserted using the MongoDB shell.

Prerequisites

  • You should have MongoDB installed and running.
  • It’s recommended that you create a database and collection to experiment with as you follow along.
  • Some command line experience is recommended.

Goal

We always like to start out with an explicit goal to make sure we hit our mark by the end of the tutorial. Our goal for this tutorial is to create a demoCollection in our demoDatabase and then sort the data by the order each document was inserted. We will show both a sort from most recent to oldest and also oldest to most recent.

1. Create collection

Note: If have collection you can skip but we’ll create collection so you can see order they were inserted.

To keep it simple we’ll insert 3 documents into a demoCollection. Order is important so this is the order we insert Alfred, Brielle, then Collin. Each document has a name and an age.

 > use demoDatabase
switched to db demoDatabase
 > db.createCollection("demoCollection")
{ "ok" : 1 }
 > db.demoCollection.insertOne({name:"Alfred", age:88})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("5c7ead734149bb2c31059d3c")
}
 > db.demoCollection.insertOne({name:"Brielle", age:43})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("5c7ead804149bb2c31059d3d")
}
 > db.demoCollection.insertOne({name:"Collin", age:19})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("5c7ead914149bb2c31059d3e")
}
 > db.demoCollection.find()
{
        "_id" : ObjectId("5c7ead734149bb2c31059d3c"),
        "name" : "Alfred",
        "age" : 88
}
{
        "_id" : ObjectId("5c7ead804149bb2c31059d3d"),
        "name" : "Brielle",
        "age" : 43
}
{
        "_id" : ObjectId("5c7ead914149bb2c31059d3e"),
        "name" : "Collin",
        "age" : 19
}

We executed a find command at the end to verify our collection contains those documents.

2. Sort using $natural

Now to sort demoCollection in the order they were inserted use the .sort() method passing it a document with $natural set to 1 for the natural order which means oldest to newest.

> db.demoCollection.find().sort({ $natural: 1 })
{
        "_id" : ObjectId("5c7ead734149bb2c31059d3c"),
        "name" : "Alfred",
        "age" : 88
}
{
        "_id" : ObjectId("5c7ead804149bb2c31059d3d"),
        "name" : "Brielle",
        "age" : 43
}
{
        "_id" : ObjectId("5c7ead914149bb2c31059d3e"),
        "name" : "Collin",
        "age" : 19
}

To do the reverse sort just swap 1 for -1 which will give reverse natural order which is the most recently inserted document to oldest.

>db.demoCollection.find().sort({ $natural: -1 })
{
        "_id" : ObjectId("5c7ead914149bb2c31059d3e"),
        "name" : "Collin",
        "age" : 19
}
{
        "_id" : ObjectId("5c7ead804149bb2c31059d3d"),
        "name" : "Brielle",
        "age" : 43
}
{
        "_id" : ObjectId("5c7ead734149bb2c31059d3c"),
        "name" : "Alfred",
        "age" : 88
}

Learn More

To learn more about the sorting and natural order we suggest you look up the MongoDB documentation directly or you can always reach out to an expert at Object Rocket to discuss your specific application.

Conclusion

In this tutorial we showed you how to sort a collection by the natural order which means oldest to newest. We also showed you how to do the inverse sort of newest to oldest. Again, this type of query is everywhere. Think of all the sites you see where when you click on the created date column header it changes between sorting from newest to oldest and oldest to newest. If you’d like to learn more about other sort options, the MongoDB documentations is fairly straightforward and can answer many of your questions. We hope this tutorial was able to answer your question about how to sort by the order inserted or maybe provide you the snippet of code that you were looking for. Thank you for your time and if you have any feedback or questions do not hesitate to reach out to us.

Pilot the ObjectRocket Platform Free!

Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.

Get Started

Keep in the know!

Subscribe to our emails and we’ll let you know what’s going on at ObjectRocket. We hate spam and make it easy to unsubscribe.