Python's MongoDB module Pymongo how-to collection

Source: Internet
Author: User
Before you start, of course, import modules:

>>> Import Pymongo

Next, the installation and startup of the local MongoDB server must be completed before you can continue.

Connections Built on Mongoclient:

Client = mongoclient (' localhost ', 27017) # or client = mongoclient (' mongodb://localhost:27017/')

Get the database:

>>> db = client.test_database# or >>> db = client[' test-database ']

Get a collection of data:

Collection = db.test_collection# or collection = db[' test-collection ')

The data in MongoDB uses a JSON-style document like this:

>>> Import datetime>>> post = {"Author": "Mike",...     " Text ":" My First blog post! ",...     " Tags ": [" MongoDB "," Python "," Pymongo "],...     " Date ": Datetime.datetime.utcnow ()}

Insert a document:

>>> posts = db.posts>>> post_id = Posts.insert_one (POST) .inserted_id>>> Post_idobjectid (' ...')

Find a piece of data:

>>> Posts.find_one () {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 ']}>>> posts.find_one ({"Author": "Mike"}) { 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 ']}>>> posts.find_one ({"Author": "Eliot"}) >>>

To find by Objectid:

>>> Post_idobjectid (...) >>> Posts.find_one ({"_id": post_id}) {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 '}

Do not convert the Objectid type to string:

>>> post_id_as_str = str (post_id) >>> Posts.find_one ({"_id": Post_id_as_str}) # No result>>>

What if you have a post_id string?

From Bson.objectid import objectid# the web framework gets post_id from the URL and passes it as a stringdef get (post_id):  # Convert from string to ObjectId:  document = Client.db.collection.find_one ({' _id ': ObjectId (post_id)})

Multiple inserts:

>>> new_posts = [{"Author": "Mike",...        " Text ":" Another post! ",...        " Tags ": [" Bulk "," Insert "],...        " Date ": Datetime.datetime (one, one, one, one)},...       {"Author": "Eliot",...        " Title ":" MongoDB is Fun ",...        " Text ":" and Pretty Easy Too! ",...        " Date ": Datetime.datetime (one, ten, ten,}]>>>) result = Posts.insert_many (new_posts) >>> Result.inserted_ids[objectid (' ... '), ObjectId (' ... ')]

To find more than one piece of data:

>>> for post in Posts.find (): ...  Post ... {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 ']}{u ' Date ': Datetime.datetime (one, one, one, one, one), U ' text ': U ' another post! ', U ' _id ': O Bjectid (' ... '), U ' author ': U ' Mike ', U ' tags ': [u ' bulk ', u ' insert ']}{u ' date ': Datetime.datetime (one, one, ten, ten), U ' te XT ': U ' and pretty easy too! ', U ' _id ': ObjectId (' ... '), U ' author ': U ' Eliot ', U ' title ': U ' MongoDB is fun '}

Of course, you can also constrain the search criteria:

>>> for post in Posts.find ({"Author": "Mike"}):  ... Post ... {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 ']}{u ' Date ': Datetime.datetime (one, one, one, one, one), U ' text ': U ' another post! ', U ' _id ': O Bjectid (' ... '), U ' author ': U ' Mike ', U ' tags ': [u ' bulk ', u ' Insert ']}

Gets the number of data bars for the collection:

>>> Posts.count ()

or the number of data bars that satisfy some sort of search criteria:

>>> Posts.find ({"Author": "Mike"}). Count ()

Range lookup, such as time range:

>>> d = datetime.datetime (one, one, and one) >>> for post in Posts.find ({"date": {"$lt": D}}). Sort ("author "):...  Print Post ... {u ' date ': Datetime.datetime (All, one, ten, Ten,), U ' text ': U ' and pretty easy too! ', U ' _id ': ObjectId (' ... '), U ' author ': U  ' Eliot ', U ' title ': U ' MongoDB is fun '}{u ' date ': Datetime.datetime (one, one, one, one, one), U ' text ': U ' another post! ', U ' _id ': ObjectId (' ... '), U ' author ': U ' Mike ', U ' tags ': [u ' bulk ', u ' Insert ']}

$lt is less than the meaning.

How do I build an index? For example, the following search:

>>> Posts.find ({"date": {"$lt": D}}). Sort ("Author"). Explain () ["Cursor"]u ' basiccursor ' >>> Posts.find ({"date": {"$lt": D}}). Sort ("Author"). Explain () ["nscanned"]

To build an index:

>>> from Pymongo import Ascending, descending>>> posts.create_index (["Date", descending), ("Author" , ascending)]) u ' date_-1_author_1 ' >>> posts.find ({"date": {"$lt": D}}). Sort ("Author"). Explain () ["Cursor"] U ' btreecursor date_-1_author_1 ' >>> posts.find ({"date": {"$lt": D}}). Sort ("Author"). Explain () ["nscanned"]

Connection Aggregation

>>> account = db. account# or >>> account = db["Account"]

View all aggregation names

>>> Db.collection_names ()

View a single record of a cluster

>>> db. Account.find_one () >>> db. Account.find_one ({"UserName": "Keyword"})

To view a clustered field

>>> db. Account.find_one ({},{"UserName": 1, "Email": 1}) {u ' UserName ': U ' libing ', U ' _id ': ObjectId (' 4ded95c3b7780a774a099b7c ') ), U ' Email ': U ' libing@35.cn '} >>> db. Account.find_one ({},{"UserName": 1, "email": 1, "_id": 0}) {u ' UserName ': U ' libing ', u ' email ': U ' libing@35.cn '}

View multiple records in a cluster

>>> for item in DB. Account.find ():    item >>> for item in DB. Account.find ({"UserName": "Libing"}):    item["UserName"]

To view aggregated record statistics

>>> db. Account.find (). Count () >>> db. Account.find ({"UserName": "Keyword"}). Count ()

Sorting Clustered Query Results

>>> db. Account.find (). Sort ("UserName") #默认为升序 >>> db. Account.find (). Sort ("UserName", Pymongo. Ascending)  #升序 >>> db. Account.find (). Sort ("UserName", Pymongo. Descending) #降序

Clustered query results multi-column sorting

>>> db. Account.find (). Sort ([("UserName", Pymongo. Ascending), ("Email", Pymongo. Descending)])

Add a record

>>> db. Account.insert ({"AccountID": +, "UserName": "Libing"})

Modify a record

>>> db. Account.update ({"UserName": "Libing"},{"$set": {"Email": "Libing@126.com", "Password": "123"}})

Deleting records

>>> db. Account.remove ()  --Delete all >>> db. Test.remove ({"UserName": "Keyword"})
  • 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.