Before we talk about indexing, let’s add a little bit of knowledge, that is, data sampling.

Random sampling

You can use the $sample operator to sample the document at random. The effect will be different each time it is executed.

Select 2 elements at random
db.employees.aggregate({$sample: {size: 2}});
Copy the code

Similarly, you can use the $match operator to match conditions for random filtering (which can be used for layered sampling).

# Select 2 elements at random from people older than 30
db.employees.aggregate(
	{
  	$match: {age: {$gt: 30}}}. 
    {$sample: {size: 2}});
Copy the code

View index

You can use db.collection.getIndexes() to view the current index of the dataset.

db.employees.getIndexes();
Copy the code

The result is as follows (note that version 4.4 returns one more NS field below) :

[{"v" : 2."key" : { "_id" : 1 }, 
  	"name" : "_id_"}]Copy the code

_ID is the unique index created by default.

Create indexes

Create an index using db. Collections. CreateIndex ({key: 1}), one for the index ascending, 1 in descending order.

db.employees.createIndex({dept: 1});
Copy the code

Looking at the index again, you can see the following results:

[{"v" : 2."key" : {
			"_id" : 1
		},
		"name" : "_id_"
	},
	{
		"v" : 2."key" : {
			"dept" : 1
		},
		"name" : "dept_1"}]Copy the code

You can also specify the name of the index, which is used to describe the index.

db.employees.createIndex({ age: - 1},  {name: 'Age descending index'});
Copy the code

The hash index

You can specify indexes in hash mode, which is more efficient for equality queries, but less efficient for range queries. You can specify both a hash and an ascending descending index for the same field (the actual descending index can also be created at the same time).

db.employees.createIndex({ age: 'hashed'},  {name: 'Age hash index'});
Copy the code

Querying the index shows that two indexes are created on age.

[{"v" : 2."key" : {
			"_id" : 1
		},
		"name" : "_id_"
	},
	{
		"v" : 2."key" : {
			"dept" : 1
		},
		"name" : "dept_1"
	},
	{
		"v" : 2."key" : {
			"age" : - 1
		},
		"name" : "Age descending index"
	},
	{
		"v" : 2."key" : {
			"age" : "hashed"
		},
		"name" : "Age hash index"}]Copy the code

Remove the index

You can remove an index using either the index name or the field index type, both using the dropIndex operation.

# delete by index name: age hash index
Db.employees. dropIndex(' age hash index ');
# Delete by field: descending index by age
db.employees.dropIndex({age: - 1});
Copy the code

conclusion

In terms of index operation, MongoDB index is more simple, flexible and diverse than SQL. In practice, you can use indexes to speed up query. The operations on other indexes will be described later.