Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

Now let’s start practicing mongodb’s indexes

Data preparation

InsertMany (db.mydoc.insertmany ()) inserts multiple pieces of data into the mydoc collection, which didn’t exist before, and mongodb will create the collection by default

Db.mydoc. insertMany([{item:"canvas", qty:120, size:{h:28, w:35.5, uom:"cm"}, status:"A", createDate:ISODate("2016-02-06T20:20:13Z") }, { item:"journal", qty:25, tags:[ {tag:"gray", type:"paper"}, {tag:"red", type:"electron"} ], size:{ h:14, w:21, uom:"cm" }, status:"A", createDate:ISODate("2016-02-07T20:20:13Z") }, {item: "the notebook", qty: 50, tags: [{tag: "yellow," type: "paper"}, {tag: "green," type: "electron"}], size: {h: 8.5, w: 11, uom:"in" }, status:"P", createDate:ISODate("2016-02-08T20:20:13Z")}, { item:"paper", qty:100, tags:[{tag:"yellow", Type: "paper"}, {tag: "brown", type: "electron"}], size: {h: 8.5, w: 11, uom: "in"}, status: "D", createDate:ISODate("2016-02-09T20:20:13Z") }, { item:"planner", qty:75, tags:[{tag:"yellow", type:"paper"}, {tag: "green" type, "electron"}], size: {h: 22.85, w: 30, uom: "cm"}, status: "D", createDate:ISODate("2016-02-10T20:20:13Z") }, { item:"postcard", qty:45, tags:[{tag:"black", type:"paper"}, {tag: "green" type, "electron"}], size: {h: 10, w: 15.25, uom: "cm"}, status: "P", createDate:ISODate("2016-02-11T20:20:13Z") }, { item:"sketchbook", qty:80, status:"A", createDate:ISODate("2016-02-12T20:20:13Z") } ]);Copy the code

Insert the success

Single field index

Use a single-field index to query items by item name

db.mydoc.createIndex({item:1})
Copy the code

Use db.mydoc.getIndexes() to check all indexes. You can see the index item_1 we just created, where _id_ is the default index

> db.mydoc.getIndexes()
[
        {
                "v" : 2,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "mytest.mydoc"
        },
        {
                "v" : 2,
                "key" : {
                        "item" : 1
                },
                "name" : "item_1",
                "ns" : "mytest.mydoc"
        }
]
>
Copy the code

Let’s query the data to see if the index hits

> db.mydoc.find().sort({item:1}).explain()
Copy the code

[MaxKey, MinKey] [MaxKey, MinKey] [MaxKey, MinKey] [MaxKey, MinKey] [MaxKey, MinKey] [MaxKey, MinKey] [MaxKey, MinKey] [MaxKey, MinKey] [MaxKey, MinKey] [MaxKey, MinKey] [MaxKey, MinKey

Try not to add sort

If db.mydoc.find().explain() doesn’t hit the index, mongodb will default to the full-text index

The composite index

The order of indexes is related to query sorting

Create a compound index with the status field ascending and the QTY field descending

db.mydoc.createIndex({status:1, qty:-1})
Copy the code

As we create an index that goes up and down, the query sort pattern must match or reverse the pattern of the index key, which means that when we query,

Either {status:-1, qty:1} or {status:1, qty:-1},

But not {status:-1, qty:-1} nor {status:1, qty:1}

Because this query order is inconsistent with our index, these two patterns cannot be indexed

TLL index

Data preparation

Create a new log set, insert multiple pieces of data, along with the last modified time

db.eventlog.insert( [ {system:"trade", lastModifiedDate:ISODate("2017-11-12T20:20:13Z"), context:"NullPointException, "}, {system:"goods", lastModifiedDate:ISODate("2017-11-15T20:21:13Z"), context:"NullPointException, "}, {system:"mongodb", lastModifiedDate:ISODate("2017-11-16T20:22:13Z"), Context: "the 2019-11-12 18:18:52. 426. [the main] the DEBUG org. The mongo. The driver. The connection - Closing the connection connectionId{localValue:2, serverValue:2409}"} ] )Copy the code

The execution result

Check out eventLog

> db.eventlog.find(){ "_id" : ObjectId("615eb334631f5c41fb6c6c16"), "system" : "trade", "lastModifiedDate" : ISODate("2017-11-12T20:20:13Z"), "context" : "NullPointException, " } { "_id" : ObjectId("615eb334631f5c41fb6c6c17"), "system" : "goods", "lastModifiedDate" : ISODate("2017-11-15T20:21:13Z"), "context" : "NullPointException, " } { "_id" : ObjectId("615eb334631f5c41fb6c6c18"), "system" : "mongodb", "lastModifiedDate" : ISODate("2017-11-16T20:22:13Z"), "context" : "The 2019-11-12 18:18:52. [the main] 426 DEBUG org. The mongo. Driver. The connection - Closing the connection connectionId {localValue: 2. serverValue:2409}" }Copy the code

Create a TLL index

The index field is a date or an array of dates. Otherwise, the document will not be deleted

Set expiration after 30 seconds, session, log, and delete collection after session expiration

> db.eventlog.createIndex({"lastModifiedDate":1}, {expireAfterSeconds:30})
Copy the code

After 30 s, we will query the data again

db.eventlog.find()
Copy the code

As expected, the query results, document data was deleted, index will still be in?

> db.eventlog.getIndexes()
Copy the code

A hash index

Data preparation

Insert some data

Db.mydoc. insertMany([{item:"canvas", qty:120, size:{h:28, w:35.5, uom:"cm"}, status:"A", createDate:ISODate("2016-02-06T20:20:13Z") }, { item:"journal", qty:25, tags:[ {tag:"gray", type:"paper"}, {tag:"red", type:"electron"} ], size:{ h:14, w:21, uom:"cm" }, status:"A", createDate:ISODate("2016-02-07T20:20:13Z") }, {item: "the notebook", qty: 50, tags: [{tag: "yellow," type: "paper"}, {tag: "green," type: "electron"}], size: {h: 8.5, w: 11, uom:"in" }, status:"P", createDate:ISODate("2016-02-08T20:20:13Z")}, { item:"paper", qty:100, tags:[{tag:"yellow", Type: "paper"}, {tag: "brown", type: "electron"}], size: {h: 8.5, w: 11, uom: "in"}, status: "D", createDate:ISODate("2016-02-09T20:20:13Z") }, { item:"planner", qty:75, tags:[{tag:"yellow", type:"paper"}, {tag: "green" type, "electron"}], size: {h: 22.85, w: 30, uom: "cm"}, status: "D", createDate:ISODate("2016-02-10T20:20:13Z") }, { item:"postcard", qty:45, tags:[{tag:"black", type:"paper"}, {tag: "green" type, "electron"}], size: {h: 10, w: 15.25, uom: "cm"}, status: "P", createDate:ISODate("2016-02-11T20:20:13Z") }, { item:"sketchbook", qty:80, status:"A", createDate:ISODate("2016-02-12T20:20:13Z") } ]);Copy the code

Creating a Hash index

> db.mydoc.createIndex({item:"hashed"})
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 1,
        "numIndexesAfter" : 2,
        "ok" : 1
}

Copy the code

Check whether the hash index matches

> db.mydoc.find({item:"paper"}).explain()
Copy the code

As shown in the figure, IXSCAN indicates that the hash index has been matched

Spatial index

There are two dimensional index and sphere index, the official website can see here

Docs.mongodb.com/manual/core…

Let’s practice sphere indexing

Sphere space index, 2dsphere.

Support for GeoJSON, traditional coordinate type data, like positions on a globe.

GeoJSON data

Coordinates specify the coordinate location and type specifies the coordinate type

Type has the following three forms

  • point

For example: location: {type: “Point”, coordinates: [-33.856077, 30.848447]}

  • lineString

Coordinates: [[40, 5], [41, 6]]} Location: {type: “LineString”, coordinates: [[40, 5], [41, 6]]}

  • polygon

For example: ‘location: {type: “Polygon”,

coordinates: [ [ [ 0 , 0 ] , [ 3 , 6 ] , [ 6 , 1 ] , [ 0 , 0 ] ] ]

} `

Traditional coordinate data

A single field specifies the coordinate position.

GeoJSON data and traditional coordinate data are two types of data. The storage mode of latitude and longitude must be the array form of [longitude, latitude]

Start practice, data preparation

Insert two document data into the Places collection

Db.places. Insert ([{loc:{type:"Point", coordinates:[-73.97, 40.77]}, name:"Central Park", category:"Parks"}, {LOc :{type:"Point", coordinates:[-73.88, 40.78]}, name:"La Guardia Airport", category:"Airport"}]);Copy the code

Create sphere space index

db.places.createIndex( { loc:"2dsphere" } )
Copy the code

View index

> db.places.getIndexes()
Copy the code

Create a composite index for a spatial index

Descending by category and ascending by name

db.places.createIndex( { loc:"2dsphere" , category:-1, name:1 } )
Copy the code

You can see this by looking at the index

Welcome to like, follow and favorites

Friends, your support and encouragement, I insist on sharing, improve the quality of the power

All right, that’s it for this time

Technology is open, our mentality, should be more open. Embrace change, live in the sun, and strive to move forward.

I am Nezha, welcome to like, see you next time ~