Python Operations Database MongoDB

Source: Internet
Author: User
Tags modifier mongoclient

Python Operations database Mongodb

First, installation Pymongo

installation Python 's MongoDB module Pymongo

1. Source Code Installation:

https://pypi.python.org/packages/69/8a/2384c55f4bd494eeb6104a9b35c36714ba1178dcd08ee5a73b92eed3d8c1/ Pymongo-3.6.0.tar.gz#md5=2f64fa7691c77535b72050704cc12afb

Unzip the installation package and go to the unzip directory to execute the installation command

Python setup.py Install

2.pip Installation

Pip Install Pymongo

Or

Easy_install Pymongo

Second, use Pymongo Operation Mongodb

1. Import Module

>>> Import Pymongo

2, establish the connection of Mongodbclient

>>> client = Pymongo. Mongoclient ("localhost", 27017)

Or

>>> client = Pymongo. Mongoclient ("mongodb://localhost:27017/")

3. Get the database

Db=client.mydb

Or

db=client["MyDB"]

4. Get Set

Books=db.my_collection

Or

books=db["My_collection"]

Inquire

query a piece of data using Find_one ():

>>> Books.find_one () {u ' lang ': U ' Python ', U ' _id ': ObjectId (' 554f0e3cf579bc0767db9edf '), U ' author ': U ' qiwsir ' , U ' title ': U ' from beginner to master '}

to query all data, use find ():

>>> for I in Books.find (): ... print I ... {u ' lang ': U ' Python ', U ' _id ': ObjectId (' 554f0e3cf579bc0767db9edf '), U ' author ': U ' qiwsir ', U ' title ': U ' from beginner to Master '}{u ' lang ': U ' 中文版 ', U ' title ': U ' physics ', U ' _id ': ObjectId (' 554f28f465db941152e6df8b '), U ' author ': U ' Newton '}

There is a find () method in the object referenced by books , which returns an iterative object that contains all the documents in the collection.

Conditional query:

>>> books.find_one ("lang": "Python") {u ' lang ': U ' python ', U ' _id ': ObjectId (' 554f0e3cf579bc0767db9edf '), U ' author ': U ' qiwsir ', U ' title ': U ' from beginner to master '}

Query result Sort:

>>> for I in Books.find (). Sort ("title", Pymongo. Ascending): ..... print I ... {u ' lang ': U ' python ', U ' _id ': ObjectId (' 554f0e3cf579bc0767db9edf '), U ' author ': U ' qiwsir ', U ' title ': U ' from beginner to Master '}{u ' lang ': U ' 中文版 ', U ' title ': U ' physics ', U ' _id ': ObjectId (' 554f28f465db941152e6df8b '), U ' author ': U ' Newton '}

This is arranged in ascending order of the value of "title", note the second parameter in sort () , meaning ascending. If you follow the descending order, you will need to modify the parameter to pymongo.desceding, or you can specify more than one sort key.

Number of statistics documents

>>> Books.find (). Count () 2

There are currently 2 data

each document in MongoDB is essentially a class dictionary structure of "key-value pairs." This structure, once read by Python , can be manipulated in a variety of ways in the dictionary. Similarly, there is something called json , which you can read in the standard library (8) in the Luzhang module of the first quarter of this tutorial . However, if you read it in Python, you cannot manipulate the document directly with the Json.dumps () method in the JSON module . One solution is to delete the ' _id ' key value pair in the document (for example:del doc[' _id ') and then use json.dumps () . The reader also uses the Json_util module because it is the "Tools forusingPython's JSON module with BSON documents", please read the instructions for using the module in/c12>http://api.mongodb.org/python/current/api/bson/json_util.html.

Inserting data

Insert 1 data:

>>> b2 = {"title": "Physics", "Author": "Newton", "Lang": "中文版"}>>> Books.insert (B2) ObjectId (' 554F28F465DB941152E6DF8B ')

To insert data in bulk:

>>> N1 = {"title": "Java", "name": "Bush"}>>> n2 = {"title": "Fortran", "name": "John Warner Backus"}>&  gt;> n3 = {"title": "Lisp", "name": "John McCarthy"}>>> n = [N1, N2, n3]>>> n[{' name ': ' Bush ', ' title ': ' Java '}, {' name ': ' John Warner Backus ', ' title ': ' Fortran '}, {' name ': ' John McCarthy ', ' title ': ' Lisp '}]>>> book S.insert (n) [ObjectId (' 554f30be65db941152e6df8d '), ObjectId (' 554f30be65db941152e6df8e '), ObjectId (' 554f30be65db941152e6df8f ')]

Update

for existing data, updating is a common operation in the database. For example, to update the name of the Hertz document:

>>> books.update ({"Name": "Hertz"}, {"$set": {"title": "New Physics", "Author": "Hertz"}}) {u ' updatedexisting ' : True, U ' ConnectionID ': 4, U ' OK ': 1.0, U ' err ': None, U ' n ': 1}>>> books.find_one ({"Author": "Hertz"}) {u ' title ': U ' New physics ', U ' _id ': ObjectId (' 554f2b4565db941152e6df8c '), U ' name ': U ' Hertz ', U ' author ': U ' Hertz '}

at the time of the update, a $set modifier was used, which can be used to specify the key value, which is created if the key does not exist.

About modifiers, not just this one, but anything else.

Modifier

Describe

$set

$unset

delete a key completely

$inc

$push

array modifier can only manipulate the value of an array, there is a key at the end of the value of adding an element, does not exist to create a list

Delete

Delete can be used with the Remove () method:

>>> Books.remove ({"Name": "Bush"}) {u ' ConnectionID ': 4, U ' OK ': 1.0, U ' err ': None, U ' n ': 1}>>> Books.find_one ({"Name": "Bush"}) >>>

This is to delete all of that document. Of course, can also be based on the rules of MongoDB syntax, write a condition, according to the conditions to delete.

Index

The purpose of the index is to make queries faster, and of course, in specific project development, whether or not the index is indexed depending on the situation. Because there is a price to build the index.

>>> Books.create_index (["title", Pymongo. Descending),] u ' title_-1 '

Python Operations Database MongoDB

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.