Common query indexes of mongoDB (III)

Source: Internet
Author: User

Common query indexes of mongoDB (III)
1. _ id index is the default index created by the vast majority of sets. For each inserted data, MongoDB automatically generates a unique _ id field. > Db. jerome_2.collection.insert ({x: 2}) WriteResult ({"nInserted": 1})> db. jerome_2.collection.getIndexes () [{"v": 1, "key": {"_ id": 1}, "name": "_ id _", "ns ": "jerome. jerome_2.collection "}]> db. jerome_2.collection.findOne () {"_ id": ObjectId ("557004f1f2824fa15224e20b"), "x": 2}> 2. single-Key Index 1. single index is the most common index 2. unlike _ id indexes, single-room indexes are not automatically created.

> Db. jerome_2.collection.ensureIndex ({x: 1}) # create an index {"createdcollectionautomatautomatautomatically": false, "numIndexesBefore": 1, "numIndexesAfter": 2, "OK": 1}> db. jerome_2.collection.getIndexes () [{"v": 1, "key": {"_ id": 1}, "name": "_ id _", "ns ": "jerome. jerome_2.collection "},{" v ": 1," key ": {" x ": 1}," name ":" x_1 "," ns ":" jerome. jerome_2.collection "}]> db. jerome_2.collection.find ({x: 1}) # Use the created index to query {"_ id": ObjectId ("557005a5f2824fa15224e20c"), "x": 1, "y": 2, "z": 3}>

 

3. multi-index multi-key index and single-key index are created in the same form. The difference lies in the field value. Single-key index: the value is a single value, such as a string, number, or date. Multi-key index: the value has multiple records, such as arrays.
> Db. jerome_2.collection.getIndexes () [{"v": 1, "key": {"_ id": 1}, "name": "_ id _", "ns ": "jerome. jerome_2.collection "},{" v ": 1," key ": {" x ": 1}," name ":" x_1 "," ns ":" jerome. jerome_2.collection "}]> db. jerome_2.collection.find () {"_ id": ObjectId ("557004f1f2824fa15224e20b"), "x": 2 }{ "_ id": ObjectId ("partition"), "x ": 1, "y": 2, "z": 3}> db. jeroem_2.collection.insert ({x: [1, 2, 3, 4, 5]}) # insert an array of data. For this data, mongodb creates a multi-index WriteResult ({"nInserted ": 1 })

 

4. Composite Index
> Db. jerome_2.collection.ensureIndex ({x: 1, y: 1}) # create {"createdcollectionautomatautomatautomatically": false, "numIndexesBefore": 2, "numIndexesAfter": 3, "OK ": 1}> db. jerome_2.collection.find ({x: 1, y: 2}) # Use {"_ id": ObjectId ("557005a5f2824fa15224e20c"), "x": 1, "y": 2, "z": 3}>

 

5. Expired Index 1. Expired index: an index that will expire after a period of time. 2. After the index expires, the corresponding data will be deleted. 3. This is suitable for storing data that will expire after a period of time, such as user login information and stored logs.
> Db. expire ({time: 1 },{ expireAfterSeconds: 30}) # create an expired index. The expiration time is 30 seconds {"createdcollectionautomatautomatically": false, "numIndexesBefore": 3, "numIndexesAfter ": 4, "OK": 1}> db. jerome_2.collection.insert ({time: new Date ()}) # insert data test WriteResult ({"nInserted": 1})> db. jerome_2.collection.find () {"_ id": ObjectId ("557004f1f2824fa15224e20b"), "x": 2 }{ "_ id": ObjectId ("partition"), "x ": 1, "y": 2, "z": 3} {"_ id": ObjectId ("55700b17f2824fa15224e20e"), "time": ISODate ("2015-06-04T08: 23: 51.531Z ")}> db. jerome_2.collection.find () {"_ id": ObjectId ("557004f1f2824fa15224e20b"), "x": 2 }{ "_ id": ObjectId ("partition"), "x ": 1, "y": 2, "z": 3} {"_ id": ObjectId ("55700b17f2824fa15224e20e"), "time": ISODate ("2015-06-04T08: 23: 51.531Z ")}> db. jerome_2.collection.find () # {"_ id": ObjectId ("557004f1f2824fa15224e20b"), "x": 2} {"_ id ": objectId ("557005a5f2824fa15224e20c"), "x": 1, "y": 2, "z": 3}>

 

Use Limit 1. The value stored in the expired index field must be of the specified time type. (It must be an ISODate or ISODate array and cannot use timestamp; otherwise, it cannot be automatically deleted) 2. If the ISODate array is specified, it will be deleted at the minimum time. 3. the expired index cannot be a composite index. 4. The deletion time is not accurate. (The deletion process is not run once every 60 s by the background program, and the deletion takes some time, so there is an error) 6. full-text index: {author: "", titile; "", article: ""} create method 1. db. articles. ensureIndex ({key: "text"}) 2. db. articles. ensureIndex ({key_1: "text", key_2: "text"}) 3. db. articles. ensureIndex ({"$ **": "text"}) use 1. db. articles. find ({$ text: {$ search: "aa"}) 2. db. articles. find ({$ text: {$ search: "aa bb cc"}) # space or 3. db. articles. find ({$ text: {$ search: "aa bb-cc"}) #-cc indicates that cc 4 is not included. db. articles. find ({$ text :{$ search: "\" aa \ "bb cc" }}) # ", enclosed by quotation marks, indicating the following example:
> Db. jerome_2.ensureIndex ({"article": "text"}) # create a full-text index {"createdcollectionautomatautomatically": true, "numIndexesBefore": 1, "numIndexesAfter": 2, "OK ": 1}> db. jerome_2.insert ({"article": "aa bb cc dd ee"}) # insert test data WriteResult ({"nInserted": 1})> db. jerome_2.insert ({"article": "aa bb rr gg zz"}) WriteResult ({"nInserted": 1})> db. jerome_2.insert ({"article": "aa bb"}) WriteResult ({"nInserted": 1})> db. jerome_2.insert ({"article": "aa bb cc zz ff ww"}) WriteResult ({"nInserted": 1})> db. jerome_2.find ({$ text: {$ search: "aa" }}) # Find {"_ id": ObjectId ("5572904271c0bbd90f4ce0e2"), "article ": "aa bb rr gg zz"} {"_ id": ObjectId ("5572903371c0bbd90f4ce0e1"), "article": "aa bb cc dd ee"} {"_ id ": objectId ("5572905671c0bbd90f4ce0e4"), "article": "aa bb cc zz ff ww"} {"_ id": ObjectId ("5572904771c0bbd90f4ce0e3"), "article ": "aa bb"}> db. jerome_2.find ({$ text: {$ search: "ff" }}) {"_ id": ObjectId ("5572905671c0bbd90f4ce0e4"), "article ": "aa bb cc zz ff ww"}> db. jerome_2.find ({$ text: {$ search: "aa bb cc"}) {"_ id": ObjectId ("5572904271c0bbd90f4ce0e2"), "article ": "aa bb rr gg zz"} {"_ id": ObjectId ("5572903371c0bbd90f4ce0e1"), "article": "aa bb cc dd ee"} {"_ id ": objectId ("5572905671c0bbd90f4ce0e4"), "article": "aa bb cc zz ff ww"} {"_ id": ObjectId ("5572904771c0bbd90f4ce0e3"), "article ": "aa bb"}> db. jerome_2.find ({$ text: {$ search: "aa bb-cc"}) {"_ id": ObjectId ("5572904271c0bbd90f4ce0e2"), "article ": "aa bb rr gg zz"} {"_ id": ObjectId ("5572904771c0bbd90f4ce0e3"), "article": "aa bb"}> db. jerome_2.find ({$ text: {$ search: "\" aa \ "\" bb \ "\" cc \ ""}) {"_ id ": objectId ("5572903371c0bbd90f4ce0e1"), "article": "aa bb cc dd ee"} {"_ id": ObjectId ("5572905671c0bbd90f4ce0e4"), "article ": "aa bb cc zz ff ww"}>

 

Full-text index similarity $ meta OPERATOR: {score: {$ meta: "textScore"}. After uninstalling the query condition, you can regret the similarity of the returned results, it can be used with sort to achieve good practical results.
> Db. jerome_2.find ({$ text: {$ search: "aa bb" }}, {score: {$ meta: "textScore"}) # The higher the score, the higher the similarity. {"_ Id": ObjectId ("5572904271c0bbd90f4ce0e2"), "article": "aa bb rr gg zz", "score": 1.2} {"_ id ": objectId ("5572903371c0bbd90f4ce0e1"), "article": "aa bb cc dd ee", "score": 1.2} {"_ id": ObjectId ("5572905671c0bbd90f4ce0e4 "), "article": "aa bb cc zz ff ww", "score": 1.1666666666666667} {"_ id": ObjectId ("5572904771c0bbd90f4ce0e3"), "article ": "aa bb", "score": 1.5}> db. jerome_2.find ({$ text: {$ search: "aa bb" }}, {score: {$ meta: "textScore "}}). sort ({score: {$ meta: "textScore"}) # sort by score {"_ id": ObjectId ("5572904771c0bbd90f4ce0e3"), "article ": "aa bb", "score": 1.5} {"_ id": ObjectId ("5572903371c0bbd90f4ce0e1"), "article": "aa bb cc dd ee", "score ": 1.2} {"_ id": ObjectId ("5572904271c0bbd90f4ce0e2"), "article": "aa bb rr gg zz", "score": 1.2} {"_ id ": objectId ("5572905671c0bbd90f4ce0e4"), "article": "aa bb cc zz ff ww", "score": 1.1666666666666667}>

 

Limits 1. only one $ text query can be specified for each query. 2. $ text query cannot appear in $ nor query 3. if $ text is included in the query, hint no longer works. mongoDB does not support Chinese now. geographic location index concept: stores the locations of some points in MongoDB. After creating an index, you can search for other points by location. Category: 1. 2d index, used to store and find points on the plane 2. 2dsphere index, used to store and find vertices on the sphere: 1. find a point within a certain distance from a point. 2. Search for points contained in a region. 2d index creation: db. location. ensureIndex ({"w": "2d"}) Position representation: longitude and latitude [longitude, latitude] value range: longitude [-180,180] Latitude [-90,90] query method 1. $ near query: query the closest vertex 2. $ geoWithin query: query the vertex 1 in a certain shape. $ near Query
> Db. location. ensureIndex ({"w": "2d"}) # create a 2d index> db. location. insert ({w: [1, 1]}) # insert test data WriteResult ({"nInserted": 1})> db. location. insert ({w: [1, 2]}) WriteResult ({"nInserted": 1})> db. location. insert ({w: [2, 3]}) WriteResult ({"nInserted": 1})> db. location. insert ({w: [100,80]}) WriteResult ({"nInserted": 1})> db. location. find ({w :{$ near: [100]}) # Will be returned. Your latest vertex {"_ id": ObjectId ("5572a961aba41684d6e8826c "), "w": [1, 1]} {"_ id": ObjectId ("5572a965aba41684d6e8826d"), "w": [1, 2]} {"_ id ": objectId ("5572a970aba41684d6e8826e"), "w": [2, 3]} {"_ id": ObjectId ("5572a97aaba41684d6e8826f"), "w": [100, 80]}> db. location. find ({w :{$ near: [], $ maxDistance: 2 }}) # maxDistance restrictions can be used (near cannot use minDistance) {"_ id ": objectId ("dimensions"), "w": [1, 1]} {"_ id": ObjectId ("5572a965aba41684d6e8826d"), "w": [1, 2]}

 

2. $ geoWithin: 1. $ box: rectangle. Use {$ box: [[<x1>, <y1>], [<x2>, <y2>]} to represent 2. $ center: circle. Use {$ center: [<x1>, <y1>], r]} to indicate 3. $ polygon: polygon. Use {$ polygon: [[<x1>, <y1>], [<x2>, <y2>], [<x3>, <y3>]} indicates an example:
> Db. location. find ({w: {$ geoWithin: {$ box: [[0, 0], [3, 3] }}) # rectangle {"_ id ": objectId ("5572a965aba41684d6e8826d"), "w": [1, 2]} {"_ id": ObjectId ("5572a970aba41684d6e8826e"), "w": [2, 3]} {"_ id": ObjectId ("5572a961aba41684d6e8826c"), "w": [1, 1]}> db. location. find ({w: {$ geoWithin :{$ box: [[1, 2], [2, 3] }}) {"_ id": ObjectId ("5572a965aba41684d6e8826d "), "w": [1, 2]} {"_ id": ObjectId ("5572a970aba41684d6e8826e"), "w": [2, 3]}> db. location. find ({w: {$ geoWithin: {$ center: [[100], 100] }}) # Circle, is the radius {"_ id ": objectId ("5572a961aba41684d6e8826c"), "w": [1, 1]} {"_ id": ObjectId ("5572a970aba41684d6e8826e"), "w": [2, 3]} {"_ id": ObjectId ("5572a965aba41684d6e8826d"), "w": [1, 2]}> db. location. find ({w: {$ geoWithin :{$ center: [[1000],] }}) {"_ id": ObjectId ("5572a961aba41684d6e8826c "), "w": [1, 1]} {"_ id": ObjectId ("5572a97aaba41684d6e8826f"), "w": [100, 80]} {"_ id ": objectId ("5572a970aba41684d6e8826e"), "w": [2, 3]} {"_ id": ObjectId ("5572a965aba41684d6e8826d"), "w": [1, 2]}> db. location. find ({w: {$ geoWithin: {$ polygon: [[], [], [], []}) # polygon query (the range of polygon enclosed by each vertex) {"_ id": ObjectId ("5572a970aba41684d6e8826e"), "w": [2, 3]} {"_ id": ObjectId ("5572a961aba41684d6e8826c"), "w": [1, 1]} {"_ id": ObjectId ("watermark "), "w": [1, 2]}> db. location. find ({w: {$ geoWithin: {$ polygon: [[], [], [], [], []}) {"_ id": ObjectId ("5572a970aba41684d6e8826e"), "w": [2, 3]} {"_ id": ObjectId ("identifier"), "w ": [100, 80]} {"_ id": ObjectId ("5572a961aba41684d6e8826c"), "w": [1, 1]} {"_ id ": objectId ("5572a965aba41684d6e8826d"), "w": [1, 2]}

 

3. Use the runCommand command to query geoNear.
Db. runCommand ({getNear: <collection>, near: [x, y], minDistance :( invalid for 2d indexes) maxDistance: num:})> db. runCommand ({geoNear: "location", near: [1, 2], maxDistance: 10, num: 1}) {"results": [{"dis": 0, "obj": {"_ id": ObjectId ("5572a965aba41684d6e8826d"), "w": [1, 2]}], "stats": {"nscanned ": numberLong (1), "objectsLoaded": NumberLong (1), "avgDistance": 0, "maxDistance": 0, "time": 2}, "OK": 1}>

 

Spherical geographic location index concept: spherical geographic location index creation method: db. collection. ensureIndex ({w: "2 dsphere"}) Location representation: GeoJson: describes a point, a straight line, polygon, and other shape formats: {type: "", coordinates: [<coordinates>]} supports $ minDistance and $ maxDistance for index creation. Description of important attributes in db format. collection. ensureIndex ({param}, {param}) # The second parameter indicates the index attributes. Important attributes include name, uniqueness, sparsity, and whether to delete the index regularly. 1. name: db. collection. the default naming format of ensureIndex ({}, {name: ""}) is as follows:
> db.jerome_2.ensureIndex({x:1})> db.jerome_2.ensureIndex({y:-1})> db.jerome_2.getIndexes()[    {        "v" : 1,        "key" : {            "_id" : 1        },        "name" : "_id_",        "ns" : "jerome.jerome_2"    },    {        "v" : 1,        "key" : {            "x" : 1        },        "name" : "x_1",        "ns" : "jerome.jerome_2"    },    {        "v" : 1,        "key" : {            "y" : -1        },        "name" : "y_-1",        "ns" : "jerome.jerome_2"    }

 

Composite Index
> db.jerome_2.ensureIndex({x:1,y:-1})> db.jerome_2.ensureIndex({x:1,y:-1,z:1})> db.jerome_2.getIndexes()[    {        "v" : 1,        "key" : {            "x" : 1,            "y" : -1        },        "name" : "x_1_y_-1",        "ns" : "jerome.jerome_2"    },    {        "v" : 1,        "key" : {            "x" : 1,            "y" : -1,            "z" : 1        },        "name" : "x_1_y_-1_z_1",        "ns" : "jerome.jerome_2"    }]
Mongodb limits the index to 125 bytes, so we need to customize the index name.
> db.jerome_2.ensureIndex({x:1,y:1,z:1,m:1},{name:"normal_index"})> db.jerome_2.getIndexes()[    {        "v" : 1,        "key" : {            "x" : 1,            "y" : 1,            "z" : 1,            "m" : 1        },        "name" : "normal_index",        "ns" : "jerome.jerome_2"    }]> db.jerome_2.dropIndex("normal_index"){ "nIndexesWas" : 7, "ok" : 1 }> 

 

2. uniqueness, specified by unique: db. collection. ensureIndex ({}, {unique: true/false })
> db.jerome.ensureIndex({m:1,n:1},{unique:true}){    "createdCollectionAutomatically" : true,    "numIndexesBefore" : 1,    "numIndexesAfter" : 2,    "ok" : 1}> db.jerome.insert({m:1,n:2})WriteResult({ "nInserted" : 1 })> db.jerome.insert({m:1,n:2})WriteResult({    "nInserted" : 0,    "writeError" : {        "code" : 11000,        "errmsg" : "insertDocument :: caused by :: 11000 E11000 duplicate key error index: jerome.jerome.$m_1_n_1  dup key: { : 1.0, : 2.0 }"    }})> 

 

3. sparse: Specify db. collection. ensureIndex ({},{ sparse: true/false}). Indexes created by default are not sparse. Because MongoDB does not have a fixed format, non-existent fields may be inserted during insertion, such as x: 1. MongoDB will create an index for this non-existent field, if you do not want to find such a thing, you can specify the sparse index to true, and no index will be created for non-existent fields. This can reduce the disk space temporarily and increase the insertion speed.
> Db. jerome. insert ({"m": 1}) WriteResult ({"nInserted": 1})> db. jerome. insert ({"n": 1}) WriteResult ({"nInserted": 1})> db. jerome. find ({m: {$ exists: true}) # exists searches for records with the existence or absence of a field in the dataset {"_ id": ObjectId ("55729ec1aba41684d6e8826a "), "m": 1} {"_ id": ObjectId ("55729d5caba41684d6e88268"), "m": 1, "n": 2}> db. jerome. ensureIndex ({m: 1}, {sparse: true}) # create a sparse index {"createdcollectionautomatautomatically": false, "numIndexesBefore": 2, "numIndexesAfter": 3, "OK": 1}> db. jerome. find ({m: {$ exists: false}) # find an internal MongoDB problem. Use the following method to forcibly specify the index {"_ id": ObjectId ("55729ec7aba41684d6e8826b "), "n": 1}> db. jerome. find ({m :{$ exists: false }}). hint ("m_1") # The following record does not contain m fields, so no index is created, so no record is found>

 

Note: you cannot search for records that do not exist in this field on the sparse index.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.