当前位置:网站首页>Getting started with mongodb

Getting started with mongodb

2022-06-26 16:54:00 Comrade Xiaoqiang

One 、MongoDb Architecture of

Summary :

  1. NoSql The concept of
  2. NoSql Application scenarios of
  3. MongoDb The logical composition of

1、NoSql The concept of

NoSQL(NoSQL = Not Only SQL ), meaning “ not only SQL”, In the early days of the Internet, most of our data were stored in relational databases . Its characteristic is the standard data structure ( Predefined patterns )、 Strong oneness 、 Tables are associated with each other through foreign keys , These characteristics make our data management more clear and rigorous , But with the development of the Internet, the data is growing explosively. We need better flexibility and faster speed for the database . This is it. NoSql doable . It does not require a predefined schema , There is no primary foreign key Association 、 Support fragmentation 、 Support replica .

NoSql The classification of :

Key value (Key-Value) Storage database

This kind of database mainly uses a hash table , This table has a specific key and a pointer to a specific data .Key/value The model is for IT The advantage of the system is simplicity 、 Easy to deploy . But if DBA When only some values are queried or updated ,Key/value It's inefficient . For example :Tokyo Cabinet/Tyrant, Redis, Voldemort, Oracle BDB.

Column store database .

This part of database is usually used to deal with the massive data of distributed storage . The bond still exists , But they feature multiple columns . These columns are arranged by the families of columns . Such as :Cassandra, HBase, Riak.

Document database

The inspiration of document database comes from Lotus Notes Office software , And it's similar to the first key value store . This type of data model is a versioned document , Semi structured documents are stored in a specific format , such as JSON. Document database can As an upgrade of the key value database , Allows nesting of key values . And the query efficiency of document database is higher than that of key value database . Such as :CouchDB, MongoDb. There are also document databases in China SequoiaDB, Is open source .

graphics (Graph) database

The database of graphic structure is the same as other rows and columns and rigid structure SQL Databases are different , It's using flexible graphic models , And can be extended to multiple servers .NoSQL There is no standard query language in the database (SQL), Therefore, it is necessary to develop data model for database query . many NoSQL Databases all have REST Data interface or query API. Such as :Neo4J, InfoGrid, Infinite Graph.

2、NoSql Application scenarios of

NoSQL The database is applicable in the following cases :

1、 The data model is simple ;

2、 Need more flexibility IT System ;

3、 High requirements for database performance ;

4、 No need for high data consistency ;

  1. Based on Douban movie, give an example NoSQL Application scenarios of
    1. Analysis of the basic information of movies
    1. The relationship between movies and stars is stored

3、MongoDb The logical composition of

Architecture :

 

Comparison between logical structure and relational database :

Relational database

MongoDb

database( database )

database( database )

table ( surface )

collection( aggregate )

row( That's ok )

document( BSON file )

column ( Column )

field ( Field )

index( unique index 、 primary key )

index ( Full-text index )

join ( Primary foreign key Association )

embedded Document ( Nested documents )

primary key( Appoint 1 to N A column is used as the primary key )

primary key  ( Appoint _id field As a primary key )

aggreation(groupy)

aggreation (pipeline mapReduce)

Two 、MongoDb Installation configuration and basic commands

Summary :

  1. mongoDb Version Description
  2. mongoDb Start parameter description
  3. client Shell Use and parameter description of
  4. Basic operations of databases and collections

  1. mongoDb Community Edition description

Download address :MongoDB Community Download | MongoDB

 

# download

wget https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-4.0.5.tgz

# decompression

tar -zxvf mongodb-linux-x86_64-4.0.5.tgz

 

2.mongoDb Start parameter description

mongoDb from C++ To write , The downloaded package can be started directly

# Create database directory

mkdir -p /data/mongo

# start-up mongo

./bin/mongod --dbpath=/data/mongo/

Conventional parameters

Parameters

explain

dbpath

Database directory , Default /data/db

bind_ip

monitor IP Address , All can be accessed by default

port

Listening port , Default 27017

logpath

Log path

logappend

Append log

auth

Is to open the user password login

fork

Whether the login has been started in the background

config

Specify profile

Sample configuration file

vim mongo.conf

Content :

dbpath=/data/mongo/

port=27017

bind_ip=0.0.0.0

fork=true

logpath = /data/mongo/mongodb.log

logappend = true

auth=false

Started in profile mode

./bin/mongod -f mongo.conf

3. client Shell Use and parameter description of

# Start client Connect The default port of this machine

./bin/mongo

# Appoint IP And port

./bin/mongo --host=127.0.0.1 --port=27017

mongo shell It's a js Control desk , It can be executed js Related operations such as :

> 1+1

2

> var i=123;

> print(i)

123

>

4. Basic operations of databases and collections

  # view the database

  show dbs;

  # Switch database

  use demo;

  # Create databases and collections , Automatically when inserting data Create databases and sets

  db.friend.insertOne({name:"wukong",sex:"man"});

  # View set

  show tables;

  show collections;

  # Delete the collection

  db.friend.drop();

  # Delete database

  db.dropDatabase();

3、 ... and 、MongoDB CRUD

Summary :

  1. How to add data
  2. Data query
  3. Data modification and deletion
  4. Full text index query

  1. How to add data

About Mongodb Description of data insertion

  1. There is no need to design the model structure in order to add a database , Automatically created when inserting data .
  2. Different data field structures in the same set can be different

Insert related methods :

// Insert a single bar

db.friend.insertOne({name:"wukong",sex:"man"});

// Insert more than one

db.friend.insertMany([

{name:"wukong",sex:"man"},{name:"diaocan",sex:"woman",age:18,birthday:new Date("1995-11-02")},{name:"zixiao",sex:"woman"}

]);

// Appoint ID

 db.friend.insert([

{_id:1,name:"wokong",sex:"man",age:1},

{_id:2,name:"diaocan",sex:"women",birthday:new Date("1988-11-    11")}

  ])

2、 Data query

Summary :

    1. Condition based basic query
    2. $and、$or、$in、$gt、$gte、$lt、$lte Operator
    3. be based on sort skip limit Method to implement sorting and paging
    4. nested queries
    5. Array query
    6. Array nested query

  1. Value operation :$in、$gt、$gte、$lt、$lte $all
  1. Logical operations :$and、$or

Its value is a combination operation of multiple logics , Followed by brackets , Brackets include multiple braces .

Based on specific values

Basic query :

# be based on ID lookup

db.emp.find({_id:1101})

# Find based on attributes

db.emp.find({"name":" ruban "})

# && operation And greater than operation

db.emp.find({"job":" lecturer ","salary":{$gt:8000}})

# in operation

 db.emp.find({"job":{$in:[" lecturer "," Customer service department "]}})

# or operation

db.emp.find({$or:[{job:" lecturer "  },{job:" Customer service department "}] })

db.friend.find({$or:[{"name":"diaocan"},{age:{$gte:18}}]});

Sorting and paging :

//  sort skip limit

db.emp.find().sort({dep:1,salary:-1}).skip(5).limit(2)

nested queries :

# The wrong sample : There is no result

db.student.find({grade:{redis:87,dubbo:90 });

# The wrong sample : There is no result

db.student.find({grade:{redis:87,dubbo:90,zookeper:85} })

# Find based on composite attributes Must contain all its values And the order is from one to

db.student.find({grade:{redis:87,zookeper:85,dubbo:90} })

# Based on the specified value in the composite attribute lookup . notes : The name must be in double quotation marks

db.student.find({"grade.redis":87});

db.student.find({"grade.redis":{"$gt":80}});

Array query :

db.subject.insertMany([

{_id:"001",name:" Chenbatian ",subjects:["redis","zookeper","dubbo"]},

{_id:"002",name:" Zhang Mingming ",subjects:["redis","Java","mySql"]},

{_id:"003",name:" Xiaoyanyan ",subjects:["mySql","zookeper","bootstrap"]},

{_id:"004",name:" Li Guicai ",subjects:["Java","dubbo","Java"]},

])

# There is no result

db.subject.find({subjects:["redis","zookeper"]})

# There is no result

db.subject.find({subjects:["zookeper","redis","dubbo"]})

# Just like nested queries , Must be all values And the order is from one to

db.subject.find({subjects:["redis","zookeper","dubbo"]})

# $all The matching array contains the values of these two items . notes : The order is not required

db.subject.find({subjects:{"$all": ["redis","zookeper"]}})

notes :

# Simplify array queries

db.subject.find({subjects:"redis"})

# Simplify array queries , There is any value in the matching array . And $all Corresponding

db.subject.find({subjects:{$in: ["redis","zookeper"]}})

Array nested query :

# Basic query , All must be queried , And the sequence is from one to

db.subject2.find({subjects:{name:"redis",hour:12} })

# Specify to query the first array Class hours are greater than 12

db.subject2.find({"subjects.0.hour":{$gt:12}})

# Query any account Class hours are greater than 12

db.subject2.find({"subjects.hour":{$gt:12}})

# $elemMatch Element match , Specify that the attribute satisfies , And it does not require the sequence from one to

db.subject2.find({subjects:{$elemMatch:{name:"redis",hour:12}}})

# Any element in the array matches Not limited to the same object

db.subject2.find({"subjects.name":"mysql","subjects.hour":120})

The operator :

  1. $elemMatch: Perform logical operations on child elements

3、 Modification and deletion of data

db. surface .update( Conditions ,{ Set the value },false,false )

The operator :

  1. $set : Set the value
  1. $unset : Delete the specified field
  1. $inc: Self increasing

$set modify

# Set the value

db.emp.update({_id:1101} ,{ $set:{salary:10300}  })

# Self increasing

db.emp.update({_id:1101} ,{ $inc:{salary:200}})

# Based on the conditions Update multiple data

# Only the first item will be updated

db.emp.update({"dep":" Customer service department "},{$inc:{salary:100}})

# Update all Matching conditions

db.emp.updateMany({"dep":" Customer service department "},{$inc:{salary:100}})

$unset Delete field

 db.subject2.update({"_id":"001"},{$unset:{"subjects":1}})

Nested array modification :

Operator :

  1. $addToSet : Add to set ( Commands are case sensitive )
  1. $push: Push to collection
  1. $pull: Remove from collection
  1. $pop: Delete... From the collection Two end non tail elements .

$addToSet: Add to set , Multiple executions do not repeat the insertion

db.subject2.update({"_id":"001"},{$addToSet:{"subjects":{"name":"mongodb","hour":20}}})

$push: Push to collection , Do not judge repetition

db.subject2.update({"_id":"001"},{$push:{"subjects":{"name":"mongodb","hour":20}}})

$pull: The matching element items , Remove all from the collection

db.subject2.update({"_id":"001"},{$pull:{"subjects":{"name":"mongodb","hour":20}}})

# Match only one field

db.subject2.update({"_id":"001"},{$pull:{"subjects":{"name":"mongodb"}}})

$addToSet、$push、$pull   Can manipulate arrays , The effect is equivalent to executing the elements in the array multiple times .

db.subject2.update({"_id":"001"},{$addToSet:{"subjects":[{"name":"mongodb","hour":20},{"name":"mongodb2","hour":22}]}})

$pop: Delete... From the collection Two end non tail elements .

# -1 Delete team leader Elements

db.subject2.update({"_id":"001"},{$pop:{"subjects":-1}})

# 1 Delete end of team element

db.subject2.update({"_id":"001"},{$pop:{"subjects":-1}})

notes : The value can only be 1 or -1, Cannot be any other value

$elemMatch Delete column elements based on conditions :

# Delete id=001 in hour Greater than 10 The element of cannot be deleted

db.subject2.update({"_id":"001"},{$pull:{"subjects":{"hour":{$gt:10}}}})

# Use $elemMatch Run operator

db.subject2.update({"_id":"001"},{$pull:{"subjects": {$elemMatch:{"hour":{$gt:10}}}  }})

upsert   When updating, if the record does not exist , The insert operation will be performed

db.subject2.update({"_id":"009"},{$set:{"name":" Chen Chen "}},true)

Update multiple records :

By default ,update Only a single record will be updated , Update multiple , You need to add a fourth parameter by true, Or use

# Only the first item will be updated

db.subject2.update({},{$set:{"name":" Chen "}},true,false)

# Update all

db.subject2.update({},{$set:{"name":" Chen "}},true,true ,)

# Update all

db.subject2.updateMany({},{$set:{"name":" Chen "}})

Delete :

// Delete based on lookup

db.emp.deleteOne({_id:1101})

// Delete entire collection

db.project.drop()

// Delete Library

db.dropDatabase()

原网站

版权声明
本文为[Comrade Xiaoqiang]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202170502184418.html