MongoDB-based Python addition, deletion, modification, and query (crud)

Source: Internet
Author: User

1. Download the python driver of MongoDB.

2. Create a New py script (you can install the pydev plug-in eclipse, which is very convenient)

 

# Coding = UTF-8
Import pymongo
Connection = pymongo. Connection ("192.168.0.101", 27017)
DB = connection. Python
Print dB. Name
Print dB. my_collection

DB. my_collection.save ({"X": 10 })

DB. my_collection.save ({"X": 8 })
DB. my_collection.save ({"X": 11 })
DB. my_collection.save ({"X": 13 })
DB. my_collection.save ({"X": 14, "Y": 3 })

Print dB. my_collection.find_one ()
Print 'all data, X value'
For item in db. my_collection.find ():
Print item ["X"]
DB. my_collection.remove ({"Y": 3 });
Print 'all data after deletion, X value'
For item in db. my_collection.find ():
Print item ["X"]
DB. my_collection.update ({"X": 8 },{ "X": 2 })
Print 'all data after update, X value'
For item in db. my_collection.find ():
Print item ["X"]
Print dB. my_collection.create_index ("X ")
# Create an index Query
For item in db. my_collection.find (). Sort ("X", pymongo. ascending ):
Print item ["X"]

Print [item ["X"] For item in db. my_collection.find (). Limit (2). Skip (1)]

 

3. MongoDB does not need to manually create databases and tables, and the program will automatically create a new one before insertion. The execution result is as follows:

Python
Collection (Database (connection ('192. 168.0.101 ', 192), u'python'), u'my _ collect ')
{U 'X': 10, U' _ id': objectid ('4d2961921e66a10a940000000000 ')}
All data, X value
10
8
11
13
14
All data after deletion, X value
10
8
11
13
All data after update, X value
10
2
11
13
X_1
2
10
11
13
[2, 11]

 

4, note: More pymongo documents, follow the http://api.mongodb.org/python/1.9%2B/api/index.html

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.