First Glimpse of Python (i)--using Pymongo to connect MongoDB

Source: Internet
Author: User
Tags deprecated mongoclient

Python can operate MongoDB conveniently using the Pymongo library . In a few words,MongoDB is different from the three-layer structure of the relational structure-database--> table--and record, which is at the level of database-- Collection --document. This is not a major introduction to MongoDB usage, but here's how to use MongoDB with Python.

1. Install MongoDB and pymongo:

[[Email protected] ~]# pip install pymongo[[email protected] ~]# yum install-y mongodb-server

Start MongoDB , where --dbpath specifies the data storage directory, the default is /data/db , if the directory does not exist will be an error; --logpath Specify the log output file, The log is automatically segmented by time:

[Email protected] ~]# Mongod--dbpath=/data/mongodb/db/--logpath=/data/mongodb/mongodb.log

Note: If you do not have a pip command, you need to install it using yum :

[email protected] ~]# Yum install-y python-pip

2. Establish the connection:

[[email protected] ~]# python
>>> Import pymongo>>> client = Mongoclient ()//= Mongoclient ("localhost") in the following two ways equivalent to >>> client , 27017) >>> client = mongoclient ("mongodb://localhost:27017/")

3. Specify the database and collectionthat will be operated :

>>> db = client.test_db>>> collection = Db.test_collection

4. general operation:

4.1 Insert:

>>> mydict = {"Name": "Lucy", "Sex": "female", "job": "Nurse"}>>> Collection.insert (mydict) >> > Collection.insert_one (mydict) >>> collection.insert_many (mydict)//Will error,. Insert_many () The parameter must be in list form, Do the following packaging:>>> mylist = []>>> mylist.append (mydict) >>> collection.insert_many (mylist)//No Error


4.2 Enquiry:

. Find_one () shows the first collection that satisfies the condition, andthe result of find () is an array of objects that satisfy the condition:

>>> Collection.find ({"Name": "Lucy"}) [0]>>> Collection.find ({"Name": "Lucy"}) [1] ...

You can use the for-in loop to view:

>>> for I in Collection.find ({"Name": "Lucy"}) ... print I ... {u ' job ': U ' nurse ', U ' _id ': ObjectId (' 554bd2e1e1382306bba8ade9 '), U ' name ': U ' Lucy ', U ' sex ': U ' female '} {u ' nationality ': U ' US ', U ' age ': $, U ' _id ': ObjectId (' 554be1cce138230714d0ab0d '), U ' name ': U ' Lucy '}

To query the collection of a specified condition , you can specify one or more conditions:

>>> Collection.find_one ({"Name": "Lucy"}) >>> Collection.find_one ({"Name": "Lucy", "Sex": "Female"} )

. Count () Total statistics of results:

>>> Collection.find (). Count ()//equals Collection.count () >>> collection.find ({"Name": "Lucy"}). Count ()

Specify a condition that is greater than or equal to be queried:

>>> Collection.find ({"Age": {"$lt": 30}})

such query symbols have $lt(less than), $gt(greater than) , $lte(less than or equal), $gte(greater than or equal ), $ne (not equal to),which is associated with the native the same in MongoDB.

To sort the results of a query by criteria:

>>> Collection.find (). Sort ("age")//default, Ascending >>> collection.find (). Sort ("age", Pymongo. Ascending)//ascending >>> Collection.find (). Sort ("age", Pymongo. Descending)//Descending

Query all collection in database :

>>> db.collection_names () >>> db.collection_names (include_system_collections=flase)// Does not include system collection, generally refers to system.indexes

Note: The db here is the db = client.test_db After the connection is established .

4.3 Update:

>>> temp = Collection.find_one ({"Name": "Lucy"}) >>> Temp2 = temp.copy () >>> temp["name"] = " Jordan ">>> collection.save (temp)//or. Update (), note the form of the parameter >>> collection.update (temp, TEMP2)// Update temp to Temp2

Note: if at this point temp["_id"] already exists in the collection, then. Save () is the update operation , the same as the. Replace_one () , otherwise . Save () is the insert operation, which is the same as the. Insert_one () function.

also notethat the. Replace_one () needs to pass in two parameters, respectively, for the current document and the document to be updated with the. Update () The same (the difference between update and save for the moment, is interested in the search engine):

>>> Collection.replace_one (old_document, new_document)

4.4 Delete:

>>> Collection.remove (temp)//Even if the temp does not exist, there will be no error >>> collection.delete_one (temp) >>> Collection.delete_many (temp)//differs from. Insert_many () and does not error when temp is not a list type


Add:

1.JSON serialization and deserialization:

If you want to serialize to a standard JSON format, two ways, one way ,dumps in the JSON package :

>>> Import json>>> for I in Collection.find ("{" Name ":" Lucy "}) ... del i[" _id "]//cannot be converted directly, unrecognized Objectid ..... json.dumps (i)

the corresponding deserialization method is json.loads ()

Mode two ,bson.json_util package in the dumps:

>>> from Bson import Binary, code>>> from bson.json_util import dumps>>> dumps ([{' Foo ': [1, 2]}     ,...     {' Bar ': {' hello ': ' World '},...     {' Code ': Code ("function x () {return1;} ')},... {' bin ': Binary ("")}]) ' [{"Foo": [1, 2]}, {"bar": {"Hello": "World"}, {"code": {"$code": "function X () {return 1;}", "$scope": {}}}, {"bin": {"$bi Nary ":", "$type": "00"}] '

the corresponding deserialization method is bson.json_util.loads ()

2.Deprecated and "modern" :

in Pymongo , some methods, although not deprecated, are no longer recommended, and using these methods will not cause error , but will report warning :

__main__:1:deprecationwarning:insert is deprecated. Use Insert_one or Insert_manyinstead.

listed below are some Deprecated method and "Mordern" Method for understanding (it is recommended that you do not use Deprecated method, because it is really deprecated someday):

Deprecated "Mordern"

Insert Insert_one Insert_many

Save Replace_one Insert_one

Remove Delete_one Delete_many

Update Replace_one Update_One Update_many

Resources:

Http://api.mongodb.org/python/current/tutorial.html

Http://api.mongodb.org/python/current/api/bson/json_util.html


This article is from the "barrel of fake dog excrement" blog, please be sure to keep this source http://xitongjiagoushi.blog.51cto.com/9975742/1657096

First Glimpse of Python (i)--using Pymongo to connect 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.