$type, index and aggregation in MongoDB

MongoDB is used in recent projects, so I probably learned the basic operation. Please forgive me for the bad writing. For more details, please go to the official website: https://docs.mongodb.com/manual/aggregation/


1.1 description

The     $type operator retrieves the matching data types in the collection based on the BSON type and returns the results.

   the types that can be used in MongoDB are shown in the following table:

1.2 use

Insert some data

> db.col.insert({
    title: 'PHP course', 
    description: 'PHP Is a powerful server-side scripting language for creating dynamic interactive sites.',
    by: 'Bad programmer',
    url: 'http://www.baizhiedu.xin',
    tags: ['php'],
    likes: 200

> db.col.insert({
    title: 'Java course', 
    description: 'Java By Sun Microsystems The high-level programming language launched by the company in May 1995.',
    by: 'Bad programmer',
    url: 'http://www.baizhiedu.xin',
    tags: ['java'],
    likes: 550

> db.col.insert({
    title: 'MongoDB course', 
    description: 'MongoDB It's a Nosql database',
    by: 'Bad programmer',
    url: 'http://www.baizhiedu.xin',
    tags: ['mongodb'],
    likes: 100

> db.col.insert({
    title: 2233, 
    description: '2233 It's a B Standing',
    by: 'Bad programmer',
    url: 'http://www.baizhiedu.xin',
    tags: ['2233'],
    likes: 100

To view data in a collection:


  • If you want to get the data with title String in the "col" collection, you can use the following command:
db.col.find({"title" : {$type : 2}}).pretty();
db.col.find({"title" : {$type : 'string'}}).pretty();

The title s in the above documents are of String type. We insert a numeric type

Execute dB. Again col.find({“title” : {$type : 2}}).pretty();

db.col.find({"title" : {$type :1}}).pretty();

    from the above query results, the default value type inserted by MongoDB is Double, and we can't find it by using int

2. Index

Official documents: https://docs.mongodb.com/manual/indexes/

2.1 description

   index can greatly improve the efficiency of query. If there is no index, MongoDB must scan each file in the collection and select those records that meet the query conditions when reading data. The query efficiency of scanning the whole collection is very low, especially when processing a large amount of data, the query can take tens of seconds or even minutes, which is very fatal to the performance of the website. Index is a special data structure. Index is stored in a data set that is easy to traverse and read. Index is a structure that sorts the values of one or more columns in the database table.

2.2 principle

   basically, the indexes in MongoDB are similar to those in other database systems. MongoDB defines indexes at the collection level and supports indexing of any field or document subfield in the MongoDB collection.

2.3 operation

Query all data in the collection

Create index

 db.Set name.createIndex(keys, options)
 db.Set name.createIndex({"title":1,"description":-1})

Note: in the syntax, the Key value is the index field you want to create. 1 specifies to create the index in ascending order. If you want to create the index in descending order, specify - 1.

createIndex() receives optional parameters. The list of optional parameters is as follows:

backgroundBooleanThe indexing process will block other database operations. Background can specify the background method to create the index, that is, add the "background" optional parameter. The default value of "background" is false.
uniqueBooleanWhether the index created is unique. Specifies to create a unique index for true. The default value is false
namestringThe name of the index. If not specified, MongoDB generates an index name by connecting the field name and sort order of the index.
sparseBooleanDo not enable indexing for field data that does not exist in the document; Special attention should be paid to this parameter. If it is set to true, documents that do not contain corresponding fields will not be queried in the index field. The default value is false
expireAfterSecondsintegerSpecify a value in seconds to complete the TTL setting and set the set lifetime.
vindex versionThe version number of the index. The default index version depends on the version mongod runs when it creates the index.
weightsdocumentThe index weight value, with a value between 1 and 99999, indicates the score weight of the index relative to other index fields.
default_languagestringFor text indexing, this parameter determines the list of stop words and rules for stem and worder. Default to English
language_overridestringFor text index, this parameter specifies the field name contained in the document. The language overrides the default language, and the default value is language

Create index fields in ascending order


View collection index

db.Set name.getIndexes()

——id exists by default. For the time being, it can be understood as a primary key index

Specify index name: create an index for the age field and specify the index name


Delete all indexes of the collection

 db.Set name.dropIndexes()

2.4 composite index

Note: MongoDB supports composite indexes, in which a single index structure contains references to multiple fields in a collection document.

Create composite index:

db.collection.createIndex( { <field1>: <type>, <field2>: <type2>, ... } )

Note: the consistency between composite index and traditional relational database in mongoDB is the left prefix principle

3. Aggregate

3.1 description

   aggregation in MongoDB is mainly used to process data (such as statistical average, summation, etc.) and return calculated data results. It is similar to count(*) in SQL statement.

3.2 use

First insert the following data into the collection

   title: 'MongoDB Overview', 
   description: 'MongoDB is no sql database',
   by_user: 'runoob.com',
   url: 'http://www.runoob.com',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 100
   title: 'NoSQL Overview', 
   description: 'No sql database is very fast',
   by_user: 'runoob.com',
   url: 'http://www.runoob.com',
   tags: ['mongodb', 'database', 'NoSQL'],
   likes: 10
   title: 'Neo4j Overview', 
   description: 'Neo4j is no sql database',
   by_user: 'Neo4j',
   url: 'http://www.neo4j.com',
   tags: ['neo4j', 'database', 'NoSQL'],
   likes: 750

Batch insert command:

3.3 common aggregate expressions

1. According to by_user field grouping


2. Count the number of articles by each author in groups


3. First according to by_ Group the user field, and then find the average value of each group of likes fields


4. First according to by_ Group the user field, and then find the minimum value of each group of likes fields


5. First according to by_ Group the user field, and then find the maximum value of each group of likes fields


6. First according to by_ Group the user field and add the url to an array


As you can see, the above values are not de duplicated. Use addToSet to de duplicate them


The pictures explained by the above parameters are from MongoDB and rookie tutorials.

Keywords: PHP Database MongoDB

Added by danscreations on Sun, 09 Jan 2022 14:27:58 +0200