mongoDB and pymongo learning

Contents of this article

The foregoing

mongoDB should be a non relational database according to the classification. This kind of database does not have the concept of traditional sql table, and naturally does not support multi table query.

install

linux Installation

The official linux installation documentation is available in here

Taking ubuntu as an example, apt install mongodb is recommended for direct installation.

docker container deployment

Pull image:

docker pull mongo:latest

Create and run a container (other parameters are set by yourself):

docker run -p 27017:27017 -d mongo:latest

Windows setup

Download mongoDB on the official website. The latest version only supports 64 bits.

Open the installation package and select Custom to customize the installation. The installation path can be modified to a non system disk. Then continue "next step" and install to the end.

Create a storage location for database files

Because before starting mongodb service, you need to create the storage folder of the database file, otherwise the command will not be created automatically and cannot be started successfully. The location of data storage is also relatively random. The command line uses the following command to start the mongodb service: mongod -- the absolute address of the dbpath data storage location. Some initialization contents will be seen in the command line. If not, check to see if the port is occupied.

Run the MongoDB server or configure the MongoDB service from the command line. Start either way.

Create a new one mongo.config And input (dbpath is the address of data storage, and logpath is the address of logging):

dbpath=D:\data
logpath=D:\MongoDB\mongo.log

Enter: mongod -- config under administrator CMD mongo.config --install --serviceName "MongoDB". According to the newly created mongo.config The profile installation service, named mongodb.

After that, you can control MongoDB by command or in "service".

Start MongoDB service

net start MongoDB

Shut down MongoDB service

net stop MongoDB

use

GUI viewer

The official MongoDB Compass is recommended. Simple and powerful. You will be prompted to install mongoDB after you install it.

Differences between mongoDB and RDBMS

sql mongoDB Description of correspondence
database database Database / database
table collection Datasheet / set
row document Data record lines / documents
column field Data fields / fields
index index Index / index
primary key _id Primary key / MongoDB will automatically_ id field set as primary key

mongoDB basic syntax

SQL statements are attached for understanding.

Query all table information

db.users.find()
select * from users

Condition query

db.users.find({"username" : "joe", "age" : 27})
select * from users where "username" = "joe" and age = 27

Query all information by criteria

db.users.find({}, {"username" : 1, "email" : 1})
select username, email from users
#Clear attention prohibition_ Return of id value
db.users.find({}, {"username" : 1, "_id" : 0})

Value range condition query

#$LT (less than) $LTE (less than or equal to) $GT (greater than) $GTE (greater than or equal to)
db.users.find({"age" : {"$gte" : 18, "$lte" : 40}})
select * from users where age >=18 and age <= 40

Unequal condition query

db.users.find({"username" : {"$ne" : "joe"}})
select * from users where username <> "joe"

Table range query

db.users.find({"ticket_no" : {"$in" : [725, 542, 390]}})
select * from users where ticket_no in (725, 542, 390)
db.users.find({"ticket_no" : {"$nin" : [725, 542, 390]}})
select * from users where ticket_no not in (725, 542, 390)

Same set multi condition query

db.users.find({"$or" : [{"ticket_no" : 725}, {"winner" : true}]})
select * form users where ticket_no = 725 or winner = true

pymongo module usage

Install pymongo

pip install pymongo

Import module

import pymongo

When doing client operation only

from pymongo import MongoClient

Establish a connection

conn = MongoClient('192.168.0.111', 27017)
//perhaps
conn = MongoClient('192.168.0.111:27017')

Connect to database

db = conn.mydb
//perhaps
db = conn['mydb']

mydb is the database to connect to, if it does not exist, create the database.

Connection selection data set

myset = db.test
//perhaps
myset = conn.mydb.test

test is the collection to be used, if not, it will be created automatically.

View all collections

db.collection_names()

View a record in a specified collection

db.Account.find_one({"key":"value"})

View fields for the specified collection

db.Account.find_one({},{"k1":v1,"k2":"v2"})

View multiple records in the specified collection

for item in db.Account.find():
    item
for item in db.Account.find({"Name":"li"}):
    item["Name"]

View specified collection record statistics

db.Account.find().count()
db.Account.find({"key":"value"}).count()

Sorting of collection query results

db.Account.find().sort("Name") #Default is ascending
db.Account.find().sort("Name",pymongo.ASCENDING) #Ascending order
db.Account.find().sort("Name",pymongo.DESCENDING) #Descending order

Multi column sorting of set query results

db.Account.find().sort([("Name",pymongo.ASCENDING),("add",pymongo.DESCENDING)])

And a find_ The method of one () returns a record that meets the conditions, while find() returns all possible contents.

Usually use find when you need to randomly extract a piece of content_ One () is more practical.

More advanced extensions

The following method appends another operation after performing the corresponding first operation.

Delete after find

find_one_and_delete()

Update after find

find_one_and_update()

Replace after find

find_one_and_replace()

Add record

db.Account.insert({"ID":21,"Name":"Ling"})

Modification record

db.Account.update({"User":"li"},{"$set":{"add":"BJ","pw":"123"}})

Delete record

db.Account.remove() #Delete all
db.Test.remove({"key":"value"}) #Specify delete

Tags: MongoDB Database Docker Linux

Posted on Fri, 26 Jun 2020 04:24:11 -0400 by vertmonkee