MongoDB's presentation
MongoDB: is based on bson (binary json) of NoSQL database
three elements of MongoDB:
Database: like MYSQL database
collections: MYSQL table similar to
the document: mysql record (row of data) like
terminal
Operation Command database:
View current database: db
View all databases: Show dbs / Show Databases
Switching database: use the database name (not to switch to the database will be created automatically)
Delete the current database: db.dropDatabase ()
Operation set of commands:
Create Collection: db.createCollection ( 'collection name') / db collection name .insert (data).
Json data format -> {Key: 'value'}
View the collection: show collections
Delete all data collection: . Db collection name .drop ()
CRUD: _id field if not manually specified will be automatically added
Insert (insert):. Db collection name .insert (document)
db.student.insert({'_id':1,name:'zhangsan'})
Save (save):. Db collection name .save (document)
db.student.save({'_id':1,name:'zhangsan'})
insert and save the similarities and differences:
the same point: if not specified _id, _id field will generate a type of ObjectID
differences: the presence of the same _id field, insert error, save the original operating cover
Update:. Db collection name .update (<query>, <update>, {multi: <boolean>})
query: update condition
update: update the data, overwrite the original data by default, if you need to use part of the update -> $ the SET
multi: whether to update the plurality, a default update only, if you want to update multiple -> {multi: to true}
Delete:. Db collection name .remove (<query>, {justOne: <boolean>})
query: delete data condition, the default delete all the data meet the conditions
justOne: specifies whether to delete only a
If you specify True, only delete a -> {justOne: true}
data query:
Search data satisfy the condition: db collection name .find ({} conditions document).
Query the first data satisfies the conditions:. Db collection name .findOne ({} conditions document)
Comparison operators:
Is equal to: -> {age: 18}
Less than: -> $ lt -> {age: {$ lt: 18}}
Less than or equal: -> $ lte
Greater than: -> $ gt
Greater than or equal: -> $ gte
It is not equal: -> $ ne
Logical Operators:
and: -.> db name set .find ({condition 1, condition 2}) -> {age: {$ gt: 18}, gender: true}
or: -> $ or -> db name set .find ({$ or: [{condition 1}, {condition 2}]).
Mixed inquiry
Range operator:
$ In: In a certain range, not interval refers list number -> {age: {$ in: [19,22,25]}}
$ Nin: not in a range -> $ nin: [,]
Regular:
// -> {name: / ^ Zhang /} -> only be used in the terminal
$ Regex -> {name: {$ regex: '^ Zhang'}} -> may be used in python
Paging query: skip limit again -> High Efficiency
limit (): used to read the specified number of documents
db. collection name .find (). limit (number)
skip (): used to skip a specified number of documents
db. collection name .find (). skip (number)
The display section Field: collection name DB .find ({}, {field name: 1, field names: 1, _id: 0}).
_id is the default display, if you do not show -> _id: 0, other fields are not displayed not write
Sort: sort the collection, 1: ascending -1: Descending
sort () -> db name set .find ({condition document}) sort ({fields: 1 / -1, the fields: 1 / -1 ...}).
Count the number of:
db. collection name .find ({condition document}). count ()
db. collection name .count ({} conditions document)
Elimination of duplicate:
distinct (): deduplication data into ⾏ -> db name set .distinct ( 'deduplication field' {} conditions document).
polymerization:
db collection name .aggregate. ({$ group: {_ id: '$ grouping field', display fields: {$ aggregation function: Value}}})
Certain fields: $ push -> to generate a list
Show the entire document: $$ ROOT
index:
建立索引:db.集合名.ensureIndex({属性名:1}) 1:升序,-1:降序
建立唯一索引:默认情况索引字段是可以重复的,可以指定索引唯一
db.集合名.ensureIndex({属性名:1},{unique:true})
查看当前集合的所有索引:db.集合名.getIndexes()
删除索引:db.集合名.dropIndex({索引字段:1}
测试索引效率:
python与MongoDB交互
1. 安装第三方插件:pip install pymongo
2. 导包:
from pymongo import MongoClient
3. 实例化mongo客户端对象:
client = MongoClient()
4. 指定集合:
collection = client['库名']['集合名']
5. 增删改查
添加一条数据: insert_one(字典)
collection.insert_one({'_id': 8, 'name': '大乔', 'hometown': '长安', 'age': 20, 'gender': False})
添加多条数据: insert_many(字典列表)
1 ls = [{'_id': 9, 'name': '凯', 'hometown': '长安', 'age': 25, 'gender': True}, 2 {'_id': 10, 'name': '苏烈', 'hometown': '长安', 'age': 30, 'gender': True}, 3 {'_id': 11, 'name': '孙策', 'hometown': '东吴', 'age': 29, 'gender': True} 4 ] 5 collection.insert_many(ls)
查找一条数据: find_one(条件字典)
print(collection.find_one({'hometown': '长安'}))
查找全部数据: find, 返回一个游标对象, 只能遍历一次
1 ret = collection.find({'hometown': '长安'}) 2 for i in ret: 3 print(i)
更新一条数据:注意使用$set命令: update_one
collection.update_one({'name': '孙尚香'}, {'$set': {'name': '甄姬'}})
更行全部数据: update_many
collection.update_many({'gender':False},{'$set':{'age':18}})
删除一条数据: delete_one
collection.delete_one({'name':'大乔'})
删除全部数据: delete_many
collection.delete_many({'gender':True})
client .close()