create index in mongodb code example

Example 1: how create an index mongodb

db.collection.createIndex({age:1}) //single field asc index on age field
db.collection.createIndex({firstName:1,lastName:-1})//compound index on firstName asc and lastName desc
db.collection.createIndex({locations:1}) //given locations is an array then a multikey index will be created

Example 2: mongodb index

db.collection.createIndex( { name: -1 } )

Example 3: golang mongo create index

col.Indexes().CreateOne(context.Background(), mongo.IndexModel{
	Keys: bson.M{"key": 1},
})