mongodb Basics Tutorial

Be refined down to learn notes, we want to help. If you have questions please correct me.

0.5 Overview

MongoDB is written in C ++ language, it is an open source database distributed file system based storage.

In the case of high load, add more nodes, you can ensure server performance.

MongoDB is designed to provide scalable, high-performance data storage solution for WEB applications.

MongoDB the data is stored as a document data structure of the key (key => value) pairs. MongoDB document similar to JSON object. Field value can contain other documents, arrays and array of documents.

Here is a comparison with the sql concepts. It can help us better understand mongodb.

SQL term / concept The term & MongoDB / concepts explain
database database database
table collection Database table / collection
row document Data rows / documents
column field Data field / fields
index index index
table joins Table join, MongoDB does not support
primary key primary key Primary keys, MongoDB automatically _id field as the primary key

To conclude, the traditional relational database content structure is

  • database
  • table
  • Row
  • Field

Mongodb is the corresponding

  • database
  • set
  • File
  • area

1.brew installation

Brew is not recommended, because now the mongodb closed source, brew mongodb already not search, but still can brew installed, do not write this.

2. official website to download

Direct Quguan network to download a zip, unzip into finished usr / local / in (control + shift +. Can show hidden folders), renamed mongodb.

Then add an environment variable can be used

$ export PATH=/usr/local/mongodb/bin:$PATH

This adds Well, anyway, is now ready to use.

Mongo can be used to test whether or not installed, if all somehow should pop version.

3. Create data / db folder

Then there is the new data / db and run the steps of the mongodb.

However, mac os catalina now there is a problem, not to write anything with the directory, so Quxianjiuguo, according to the latest solutions to mongodb is in /Users/(你的用户名)/data/db/there when the directory

Finally, bring --dbpath =, if not added by default to / data / db Lane

sudo mongod --dbpath=/Users/Wangzirui/data/db

If it is not to say that Katrina,

sudo mkdir -p /data/dbThen sudo mongodget away.

After changing catelina restrictions (closed sip). Can be directly used sudo mount -uw / change with the directory permissions, you can directly sudo mongod get away.

Then the other terminal enters / usr / loacl / mongodb / bin /

Then ./mongo started the client's mongo

Or directly mongo can.

4. Turn on creating a client service

Start the service:

sudo mount -uw /

sudo mongod

Start the client:

mongo

5. Command

5.1 db operation

  • Display Database
    • show dbs
  • Switch databases, not create a new one
    • use admin
  • It shows where you are in the database
    • Db
  • Delete your use of the current database
    • db.dropDatebase()
  • New Database
    • use database name
    • Built over show dbs will not appear immediately, because there is not just the new database data. So not show up.

5.2 collection operation

  • What is displayed in this database collection
    • show collections
  • New Collection, in the case of use of a database
    • db.createCollections(name,options)
    • Then show dbs can now see the use of the database
  • Delete a collection, in the case now Use database
    • db. You want collectionname.drop ()
    • And then deleted

5.3 document operation

collectionname on behalf of that corresponding collcetion name (mysql table called in, Mongodb was called collection, is a kind of database structure) are not now operating table is not a collection, but the collection of a data structure called the document, the document , where a document equivalent to mysql rows.

  • Riga to data collection, the new document directly
    • db.collectionname.insert({"name":"wangzirui"})
    • Increasing the plurality of brackets to add a plurality of objects on the outside of the insert, which is represented by an array of objects.
    • db.collectionname.insert([{name:"wangzirui"},{name:"laoli"}])
  • View collection of data in
    • db.collectionname.find()
  • Save, can not be given at the same _id case, then covered directly out of what was just repeating Id.
    • db.collectionsname.save({_id:1001,name:"laowang",age:22})
  • Updated document data
    • db.collectionname.update ({} current data, the replacement data {}, {} CI)
    • db.collectionname.update({name:"laotie"},{name:"ergou"})
    • This will remove other content, there is only one name: ergou so to add $ set other parameters reserved
    • db.collectionname.update({name:"laotie"},{$set:{name:"ergou"}})
    • CI Riga {Multi: true}, then add this allows a plurality of name: change with "laotie"
    • db.collectionname.update({name:"laotie"},{$set:{name:"ergou"}},{multi:true})
  • Delete the document content, if not the second argument, the default is the collection are deleted in line with the first strip.
    • Db.collectionname.remove({name:"laotie"},{justOne:true})

5.4 document query

After the above teachings can understand that, based on the database to query collections where the data is to be operated by db.collcetion_name. Method, empathy. Query on the document, when before we are used to view the collection, he is the find () method.

find which can add a parameter, it is the reality in all of the document collection without words.

  • find () method can be applied in conditions, e.g. db.collectionname.find ({age: 18})
    • If it does not look good line by line, and then may db.collectionname.find ({age: 18}) behind the increase .pretty ()
  • Comparison Operators
    • less than 小于 $lt db.collection_name.find(age:{$lt:18})
    • less than equal or less $ LTE
    • Greater than $ gt Geater than
    • $ Gte greater than or equal
    • $ Ne not equal
  • Take in the range of $ in
    • $in:[10,20,30]
    • db.collection_name.find({age:{$in:[10,20,30]}})
  • And operation
    • db.collection_name.find(age:18,name:"laotie")
  • Or operation
    • db.collection_name.find({$or:[{age:18},{name:"laotie"}]}
  • Regular
    • db.collection_name.find({age:/^1/})或者db.collection_name.find({age:$regex:"^1"})
  • And skipping limits, generally used tab
    • limit(2)
    • skip(2)
  • projection

    • Find example (here put specific parameters {}, {} where the discharge projection)
    • db.collection_name.find ({age: {$ lt: 18}}, {_ id: 0, age: 1}) would only show each object there is only one option of age
    • Note that if the projector in the _id without options, the default is automatically displayed. _Id set only to 0. If you do not want to let him display other fields not directly inside plus. Other things you want to display the property directly added to the list on the line.
  • To filter the data by function Js

    • $where:

    • db.collection_name.find({$where:function(){

      Return age>10}})

  • According to a field ordering

    • sort
    • . Db.collection_name.find () sort ({age: 1}), then descending to take if -1
  • count

    • count()

    • Directly behind the check out, plus you can display the

    • db.collection_name.find({$where:function(){

      Return age>10}}).count()

  • Deduplication

    • db.student.distinct("name",{"age" : 18})
    • This name as well as directly to the age of 18 gave deduplication

6. Backup and Recovery

Backup 6.1

Directly at the terminal input, do not enter the client's mongodb

mongodump -h hostname -d dbname -o dbdirectory

-h server address, you can specify the port number. The machine can not fill

-D database under which specific Mongodb

-o you want to save to a local where

E.g. input mongodump -d laotie -o wenjianjia termainal directly in the native

Then put the database to save this laotie Users / wangzirui / wenjianjia this folder the

6.2 recovery

Also in the direct input terminal

Mongorestore -h hostname -d dbname --dir

-h server address, you can specify the port number. The machine can not fill

-d What do you want this database is called, it is not necessarily the original name

Where -Dir this backup file

7. polymerization

aggregate, that is a pipeline, or similar middleware is a function of chained calls. Eventually export the data you want.

7.1group

A first set of data put student, all operations are polymerized in accordance with the data to.

> db.student.find()
{ "_id" : ObjectId("5e003b92f197cb08dc74a311"), "name" : "duanyuxin", "age" : 21, "sex" : "male" }
{ "_id" : ObjectId("5e003b92f197cb08dc74a312"), "name" : "baiyu", "age" : 20, "sex" : "male" }
{ "_id" : ObjectId("5e003f66f197cb08dc74a313"), "name" : "wangzirui", "age" : 22, "sex" : "male" }
{ "_id" : ObjectId("5e003f8ff197cb08dc74a314"), "name" : "zhuhuan", "age" : 22, "sex" : "female" }
{ "_id" : ObjectId("5e003f8ff197cb08dc74a315"), "name" : "caoyajing", "age" : 12, "sex" : "female" }

First put examples:

> db.student.aggregate({
     $group:{_id:"$sex",avg_age:{$avg:"$age"}}
})


{ "_id" : "male", "avg_age" : 21 }
{ "_id" : "female", "avg_age" : 17 }

In the $groupobject, the value at the beginning of the preceding field (column) which will be output on behalf of the domain. The latter $sexrepresents the group I get something as a group of keys. If I for different age groups, then I will get

> db.student.aggregate({
     $group:{_id:"$age"}
})

{ "_id" : "12"}
{ "_id" : "20"}
{ "_id" : "21"}
{ "_id" : "22"}

the result of.

Went on to say avg_age, this field is our own definition. (May be prejudiced, I always feel more comfortable with the field say, also easier to understand), what is all right, but the back $avg:"$age", which means that, first of all in front $avgis averaged to get back what you $agemean. Then, when the output is printed"avg_age:前面符合id分类的文档的age平均值"

If you want to calculate some value for the entire document, should only _id:nullthen you can not group, the direct use of the entire document to count.

> db.student.aggregate({
     $group:{_id:null,avg_age:{$avg:"$age"}}
})

{ "_id" : null, "avg_age" : 19.4 }

$sum:

Also speaking use a $ sum, and look at how to use.

> db.student.aggregate({
     $group:{_id:null,count:{$sum:1},avg_age:{$avg:"$age"}}
})

{ "_id" : null, "count" : 5, "avg_age" : 19.4 }

On the basis of just a plus $sum:1Lane $sumsuggests that it is summed with, followed by the summation of a multiple of, if you set to 2, then the results would become 10 by 2 counts, then generally used is set to 1 in general.

$ Group to re-use:

$groupYou can add more than one packet condition, may be added to a plurality of grouping conditions, if the conditions corresponding to each field of the document, then the operation is equivalent to the weight.

> db.student.aggregate({
     $group:{_id:{name:"$name",sex:"$sex",age:"$age"}}
})

Then followed by another channel for the next operation on it. But the next operation to use the property is $_id.namesimilar. Because when we went to gave weight to attribute called _id fields.

7.2$project

Reconstruction of output structure, that is, the channel characteristics aggregete, and then adjust the final output structure you want. And a projection substantially similar.

Put chestnuts:

> db.student.aggregate(
  {
      $group:{_id:null,count:{$sum:1},avg_age:{$avg:"$age"}}
    },
  {
  $project:{sex:"$_id",count:"$count",avg_age:"$avg_age"}
    }
)

{ "_id" : null, "sex" : null, "count" : 5, "avg_age" : 19.4 }

Similarly, it can be replaced with 1 or 0. For example a child is not specific, nothing big.

7.4 $match

Listen to know the name filter is used, although you can find the same filter, but you can not find out the results passed to the next pipe.

For example, you want to know it older than 20 boys and girls were several people

You may operate in the following manner

db.student.aggregate(
    {$match:{age:{$gt:19}}},
 {$group:{_id:"$sex",count:{$sum:1}}},
 {$project:{_id:0,sex:"$_id",count:1}}
)

{ "count" : 3, "sex" : "male" }
{ "count" : 1, "sex" : "female" }

Roughly like this, filled it and find something inside is the same.

7.5 $sort

Usage is consistent with common usage, directly put chestnuts:

db.student.aggregate(
    {$group:{_id:"$sex",count:{$sum:1}}},
  {$sort:{age:1}}
)

{ "_id" : "female", "count" : 2 }
{ "_id" : "male", "count" : 3 }

If other methods have read the previous, this should not be a problem. Not explained.

7.6 $limit,skip

The same with the front like, directly put examples:

db.student.aggregate(
    {$skip:2},{$limit:2}
)

{ "_id" : ObjectId("5e003f66f197cb08dc74a313"), "name" : "wangzirui", "age" : 22, "sex" : "male" }
{ "_id" : ObjectId("5e003f8ff197cb08dc74a314"), "name" : "zhuhuan", "age" : 22, "sex" : "female" }

Not explained.

8. Create an index

for(i=0;i<100000;i++){db.test.insert({name:'test'+i,age:i})}

In particular, the huge amount of data when looking for data will become slower.

So to give a set of targeted index

db.test.ensureIndex({name:1})

Then this set will have two indexes, and before that index called _id, now also added a domain name as an index.

Several operations on the index:

  • Create a unique index
    • db.test.ensureIndex({name:1},{uniqe:true})
  • Establish joint index
    • db.test.ensureIndex({name:1},{age:1})
  • View the index of the current collection
    • db.test.getIndexes()
  • Delete Index
    • db.t1.dropIndex ( "Index Name")

Guess you like

Origin www.cnblogs.com/wangzirui98/p/12089283.html