Environment settings:
[Email protected] ~]# cat/etc/redhat-release CentOS release 6.9 (Final) [[email protected] ~]# Python-vpython 2.6.6
1. First make sure that the MongoDB database is running
2. Installing the Pymongo module
Official website: https://pypi.python.org/pypi/pymongo/(download on Demand)
[Email protected] src]# wget https://pypi.python.org/packages/a3/fe/ 826348375bfe2d11c96cdc7b7cbabbd84b8b15b62eb33638ee3241fca5f9/pymongo-3.6.1.tar.gz#md5= 0d72c87fb93cea0759529befafefce54[[email protected] src]# tar-zxvf pymongo-3.6.1.tar.gz [[email protected] src]# CD Pymongo-3.6.1[[email protected] pymongo-3.6.1]# python setup.py install
3. Start writing Python scripts to connect to the MongoDB database
[email protected] ~]# cat mongodb.py
#!/usr/bin/env python#-*-coding:utf-8-*-#导入模块from Pymongo Import mongoclient# Establish a MongoDB database connection client=mongoclient (' localhost ', 27017) #test为数据库db =client.test#test as a collection, equivalent to the table name collection=db.test# Insert collection data Collection.insert ({"title": " Test "}) #打印集合中所有数据for item in Collection.find ():p rint item# Update the data in the collection collection.update ({" title ":" Test "},{" title ":" This is update Test "}" #关闭连接client. Close () #!!!! Other operations # finds single data in collection #print Collection.find_one () #删除集合collection中的所有数据 #collection.remove () #删除集合collection # Collection.drop ()
4. Execute the script, the library query whether to update the collection data
[Email protected] ~]#/opt/mongodb/bin/mongo
MongoDB Shell version v3.4.5connecting to:mongodb://127.0.0.1:27017mongodb Server version:3.4.5> use testswitched to DB test> Db.test.find () {"_id": ObjectId ("5ab174b2685a5f0b11f67b4f"), "title": "This is update test"}> #更新成功
Python connection MongoDB success!!!
Python connects to MongoDB database and performs operations