How to pick random document from Mongo DB

We need to use the aggregate function to pick a random document from Mongo DB. Its usage is simple. It accepts an array of objects. You need to pass $sample object in one array object and tell the number of random documents you want to fetch in the size object. Suppose you have the following data in your users collection.

db.users.insertOne({ name: "Adnan", language: "Java" })
db.users.insertOne({ name: "Tech", language: "Node JS" })
db.users.insertOne({ name: "Developer", language: "Java" })
db.users.insertOne({ name: "Programmer", language: "C++" })

Then the Mongo DB query to return 1 random document would be:

db.users.aggregate([
	{
		$sample: {
			size: 1
		}
	}
])

This will return 1 random document from your users collection. If you want to apply some query to it, you can do it by passing another array element and this time using the $match operator.

db.users.aggregate([
	{
		$match: {
			language: "Java"
		}
	},
	
	{
		$sample: {
			size: 1
		}
	}
])

This will return 1 random document from users collection whose language is “Java”. Make sure the $match operator is the first element of the array, otherwise it will return empty records sometimes.

Video tutorial

You can learn more about Mongo DB aggregate function from their official documentation. Check out our tutorials on Mongo DB.