This is the 10th day of my participation in the August More Text Challenge

MongoDB is a distributed storage based database, NoSQL non-relational database written by C++ language. Non-relational database NoSQL, that is, Not Only SQL, meaning “more than SQL”, usually the index data in the form of objects stored in the database, and the relationship between objects through the properties of each object itself to determine.

The characteristics of the mongo

MongoDB database is mainly used for mass storage and is often used in data collection projects. Data storage does not need fixed mode, does not need redundant operations can be horizontal expansion, low cost, no complex relationship, simple installation, support a variety of programming languages, etc.

MongoDB compared to traditional databases

Traditional database: structured data, set the table structure, the content of each row, must be consistent with the table structure, that is to say – the number of columns, types are the same.

MongoDB document database: the object stored by MongoDB is a document. The data structure is composed of key-value pairs, similar to JSON objects. The field values can contain other documents, arrays and document groups.

Here are some concepts of mongodb versus relational databases:

SQL MongoDB
database database
Table Database table The collection collection
Row Indicates the data record row The document document
Column data attribute Field (field)
The index index The index index
Primary key primary key Primary key primary key

Official document learning: docs.mongodb.com/manual/intr…

Windows After downloading the installation package, find mongo.exe in the installation directory, run it, and start it.

image-20210524135133746

Run the MongoDB server on the cli

Create a data folder in the root directory of the MongoDB disk, and create a DB folder in the data folder.

CMD, go to G:\mango\data, run mongod –dbpath G:\mango\data, and start Mongod.

Common MongoDB commands

Common Database commands

Use database_name # dropDatabase db.dropdatabase ()Copy the code

Common collection commands

# createCollection db. CreateCollection (name, options) name: create a collection name options: create parameters # createCollection show tables show collections # delete collection db. Set name.drop ()Copy the code

Common data operation commands

Insert data

Db.stu. insert({name:'zhangsan','age':20}); # insert a data, specify the primary key: db. Stu. Insert ({_id: 3, 'name' : 'lisi', 'age: 28}); # add multiple data: db. Stu. Insert ([{name: 'wangyi', 'age: 18}, {' name' : 'sunwu', 'age: 25}])Copy the code

The document format in mongodb is JSON

The id key value does not exist in the document, so the system automatically adds it to the document. _ID is a special key value that is unique throughout the collection.

Remove data db.collection.remove(query expression, option justOne)

Option justOne: (Optional) If set to true or 1, only one document will be deleted. If this parameter is not set, or the default value false is used, all documents matching the criteria will be deleted.

#db.stu. Remove ({name:"zhangsan"})
Copy the code

Modify the data

Db. Collection. The update (query expression, new value, option) options: {upsert: true/false, multi: true/false}

  • Upsert: the default value is false. Action: No record whether to insert. Same as replace in mysql
  • Multi: The default value is false
# replace the first document whose name is zhangsan with {"name":"lisi"."age":10}
db.stu.update({"name":"zhangsan"}, {"name":"lisi"."age":10}) $set modifier, specify the key to be updated, if the key does not exist, if it exists, update. # replace all documents whose name is zhangsan with {"name":"lisi"."no":'100'}
db.stu.update({"name":"zhangsan"},{$set:{"name":"lisi"."no":'100'}},{multi:true})
Copy the code

To find the data

grammar operation format
$eq Is equal to the {that}
$lt Less than {:{$lt:}}
$lte Less than or equal to {:{$lte:}}
$gt Is greater than {:{$gt:}}
$gte Greater than or equal to {:{$gte:}}
$ne Is not equal to {:{$ne:}}
$or or {$or:[{},{}]}
$in Within the scope of {age:{$in:[val1,val2]}}
$nin Out of range {age:{$nin:[val1,val2]}}
Find () # find all matched data db. Find ({conditional document}) db.stu.find({age:{$gt:16}}) # query age greater than16Records of the db. Stu. Find ({$or: [{age: {$gt:18}},{name:"xiaoming"}]) #18Db.stu. find({$where:function(){$where:function(){$where:function(){$where:function(){$where:function(){return this.age>20}}) # find().limit(NUMBER) # find().limit(NUMBER1Ascending order, parameter- 1Db.set name.find ().sort({fields:1. }) # find({condition}).count()Copy the code

Mongodb interaction with Python

Using Python to operate MongoDB is very convenient, without defining the table structure can directly insert data, using pymongo module, MongoDB and Python interaction can be realized.

Pymongo library

pip install pymongo
Copy the code

Api.mongodb.com/python/curr…

1. Connect the mongo

No permission authentication is required

import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017")
# myclient = pymongo.MongoClient('localhost'.27017)
printMyclient.list_database_names ()'admin'.'config'.'local'.'test']
Copy the code

Permission Authentication Mode

import pymongo
myclient = pymongo.MongoClient('localhost'.27017)
db = mongo_client.admin
db.authenticate('Username'.'password')
Copy the code

2. Specify the database and collection

Db = client. Test db = client.'test'Stu: collection = db['stu']
Copy the code

3. Insert data

You can use the INSERT method to insert data, but in Pymongo, insert_One is officially recommended for single data writes and insert_many for multiple data inserts.

#增加一条
stu1={'id':'001'.'name':'zhangsan'.'age':10}
result = collection.insert_one(stu1)
#增加多条
stu2={'id':'002'.'name':'lisi'.'age':15}
stu3={'id':'003'.'name':'wangwu'.'age':20}
result = collection.insert_many([stu2,stu3])
Copy the code

4. Delete data

Result = collection.remove({result = collection.remove({result = collection.remove({result = collection.remove({result = collection.remove({'name': 'zhangsan'}) # delete data from collection.delete_one() result = collection.delete_one({"name":"zhangsan"}) #delete_many() result = collection.delete_many({"age": {'$lt':20}})
Copy the code

5. Modify data

Data can be modified using the update method, but in Pymongo, update_One is officially recommended for single data changes and update_many for multiple data changes.

# update_one, first2The $type operator is used as the key name of the dictionary22
condition = {'name': 'zhangsan'}
res = collection.find_one(condition)
res['age'] = 22
result = collection.update_one(condition, {'$set': res})
print(result) # Returns an UpdateResult typeprint(result.matched_count,result.modified_count) #1, number of affected data items1
Copy the code
#update_many, all ages are15Name = xixi condition = {'age': 15}
res = collection.find_one(condition)
res['age'] = 30
result = collection.update_many(condition, {'$set': {'name':'xixi'}})
print(result) # Returns an UpdateResult typeprint(result.matched_count,result.modified_count) #3, number of affected data items3
Copy the code

6. Query data

Find () finds all data

Returns all results that meet the criteria, or all results if the criteria are empty. The result is a Cursor iterable.

rets = collection.find({"age":20}),for ret in rets:
    printCount = collection.find().count() results = collection.find().sort()'age', pymongo.ASCENDING)
print([result['age'] for result in results])
Copy the code

Find_one () finds a piece of data

Receives a dictionary condition and returns the entire column of dictionary data, or the first column if the condition is empty.

ret =collection.find_one({'name': 'zhangsan'})
Copy the code