Python connects to MongoDB database and performs operations

Source: Internet
Author: User
Tags mongoclient mongodb


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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.