Python support for MongoDb

Source: Internet
Author: User
Tags sql show tables

This article is a simple tutorial on using MongoDB in Python. We will use pymongo to make a simple summary of various operations on MongoDB. We have made a simple arrangement. If you are using Python, you can take a look.

Download the version of the corresponding platform and decompress it. For ease of use, add the bin path to the system path environment variable. Mongod is the server, mongo is the client shell, and then create a data file directory: create a data folder under drive C, which creates a db folder.

Basic usage:

Install the Driver in the corresponding language, and install pymongo in Python.

1 $ easy_install pymongo

UsageSummary, taken from the official tutorial

Create a connection

1 >>> import pymongo
2 >>> connection=pymongo.Connection('localhost',27017)

Switch Database

1 >>> db = connection.test_database

Get collection

1 >>> collection = db.test_collection

Db and collection are created in a delayed manner. They are created only when Document is added.

Add document, _ id automatically created

1 >>> import datetime
2 >>> post = {"author": "Mike",
3 ...         "text": "My first blog post!",
4 ...         "tags": ["mongodb", "python", "pymongo"],
5 ...         "date": datetime.datetime.utcnow()}
6 >>> posts = db.posts
7 >>> posts.insert(post)
8 ObjectId('...')

Batch insert

01 >>> new_posts = [{"author": "Mike",
02 ...               "text": "Another post!",
03 ...               "tags": ["bulk", "insert"],
04 ...               "date": datetime.datetime(2009, 11, 12, 11, 14)},
05 ...              {"author": "Eliot",
06 ...               "title": "MongoDB is fun",
07 ...               "text": "and pretty easy too!",
08 ...               "date": datetime.datetime(2009, 11, 10, 10, 45)}]
09 >>> posts.insert(new_posts)
10 [ObjectId('...'), ObjectId('...')]

Get all collections (equivalent to SQL show tables)

1 >>> db.collection_names()
2 [u'posts', u'system.indexes']

Obtain a single document

1 >>> posts.find_one()
2 {u'date': datetime.datetime(...), u'text': u'My first blog post!', u'_id': ObjectId('...'), u'author': u'Mike', u'tags': [u'mongodb', u'python', u'pymongo']}

Query multiple documents

View source Print?
1 >> for post in posts.find():
2 ...   post
3 ...
4 {u'date': datetime.datetime(...), u'text': u'My first blog post!', u'_id': ObjectId('...'), u'author': u'Mike', u'tags': [u'mongodb', u'python', u'pymongo']}
5 {u'date': datetime.datetime(2009, 11, 12, 11, 14), u'text': u'Another post!', u'_id': ObjectId('...'), u'author': u'Mike', u'tags': [u'bulk', u'insert']}
6 {u'date': datetime.datetime(2009, 11, 10, 10, 45), u'text': u'and pretty easy too!', u'_id': ObjectId('...'), u'author': u'Eliot', u'title': u'MongoDB is fun'}

Conditional Query

1 >>> posts.find_one({"author": "Mike"})

Advanced Query

1 >>> posts.find({"date": {"$lt": d}}).sort("author")

Count

1 >>> posts.count()
2 3

Add Index

1 >>> from pymongo import ASCENDING, DESCENDING
2 >>> posts.create_index([("date", DESCENDING), ("author", ASCENDING)])
3 u'date_-1_author_1'

View query statement Performance

1 >>> posts.find({"date": {"$lt": d}}).sort("author").explain()["cursor"]
2 u'BtreeCursor date_-1_author_1'
3 >>> posts.find({"date": {"$lt": d}}).sort("author").explain()["nscanned"]
4 2

Note that you should be careful with your summary for your reference only.

Disadvantages

  • Instead of replacing traditional databases in an all-round way (NoSQLFan: Can it replace an application scenario that needs to be viewed)
  • Does not support complex transactions (NoSQLFan: MongoDB only supports atomic operations on a single document)
  • The entire tree in the document is not easy to search. What is the limit of 4 MB? (NoSQLFan: version 1.8 has been changed to 16 MB)

Features ):

  • Document database, table structure can be embedded
  • No mode. Avoid overhead of null fields (Schema Free)
  • Distributed support
  • Regular Expressions are supported in queries.
  • Dynamic scaling Architecture
  • 32-bit versions can only store up to GB of data (NoSQLFan: The maximum file size is 2 GB, and 64-bit is recommended in the production environment)

Noun correspondence

  • A data item is called Document (NoSQLFan: corresponds to a single record in MySQL)
  • One document is embedded into another document (comment Embedded post) is called Embed
  • The place for storing a series of documents is Collections (NoSQLFan: corresponding to the table in MySQL)
  • Table Association, called Reference

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.