A simple and straightforward tutorial on Python3 operation of MongoDB

Source: Internet
Author: User
Tags mongoclient
This article mainly introduces the detailed Python3 operation MongoDB Simple and easy to understand tutorial, detailed introduction of how to connect the database and the operation of the database, there is a need to understand.

Connecting to a database

The linked database needs to provide an address and an interface. First, you will import the package.

From Pymongo Import mongoclientconn = mongoclient (' localhost ', 27017)

Of course, you can use the following notation:

conn = mongoclient (' mongodb://localhost:27017/')

Create a database

MongoDB does not need to create a good database in advance, but is used directly, if found not automatically created.

db = Conn.testdb

The above statement creates a TestDB database. However, when data is not inserted, the database is not visible in the management tool (not shown).

Inserting data

First, first we insert a piece of data to see.

Single record insertion

From Pymongo Import mongoclientconn = mongoclient (' mongodb://localhost:27017/') db = Conn.testdbdb.col.insert ({"Name": ' Yanying ', ' Province ': ' Jiangsu ', ' Age ': 25}

Note: The next operation will ignore the database connection operation, directly write the core code, please make up your own.

Python console Nothing happens, that's what success means. Using the Administrative Tools to view database records does contain a single piece of data.

Multiple record insertions

MongoDB can also insert more than one data at a time

Db.col.insert ([{"Name": ' Yanying ', ' Province ': ' Jiangsu ', ' age ': +}, {"name": ' Zhang San ', ' Province ': ' Zhejiang ', ' age ': +}, {"Name": ' Zhang 31 ', ' Province ': ' Zhejiang 1 ', ' Age ': ' 33} ', {' name ': ' 32 ', ' Province ': ' Zhejiang 2 ', ' Age ': ' 3} ', ' Name ': ' Chang ', ' ' Province ': ' Zhe jiang ', ' age ' : 28},])

Querying data

Below we will query the data just inserted.

Single Query

We can use Find_one () to query a record.

Db.col.find_one ()

The above statement can query a MONGODB record. The extra _id in the record is the unique value that MongoDB automatically generates.

Copy the Code code as follows:

{' _id ': ObjectId (' 5925351ad92fac3250b9ae3f '), ' name ': ' yanying ', ' Province ': ' Jiangsu ', ' Age ': 25}

Let's just insert some data for the following operation. (Omit tens of thousands of words)

Query all

If we need to query out all the records, we can use Db.col.find () but find out a result resource set.

We can use for to list all records.

For item in Db.col.find (): Print (item)

This will get all the records.

{' _id ': ObjectId (' 5925351ad92fac3250b9ae3f '), ' name ': ' yanying ', ' Province ': ' Jiangsu ', ' Age ': 25} {' _id ': ObjectId (' 592550e5d92fac0b8c449f87 '), ' name ': ' Zhangsan ', ' Province ': ' Beijing ', ' age ': 29} {' _id ': ObjectId (' 592550f6d92fac3548c20b1a '), ' name ': ' Lisi ', ' Province ': ' Shanghai ', ' age ': 22} {' _id ': ObjectId (' 59255118d92fac43dcb1999a '), ' name ': ' King two hemp ', ' province ': ' Guangdong ', ' age ': 30}

Conditional query

You can filter the data as long as the query condition is plugged in as a parameter.

For item in Db.col.find ({' name ': ' Yanying '}): Print (item)

Query results

The code is as follows:

{' _id ': ObjectId (' 5925351ad92fac3250b9ae3f '), ' name ': ' yanying ', ' Province ': ' Jiangsu ', ' Age ': 25}

Of course, you can also query for records that are less than a certain value

For item in Db.col.find ({' age ': {' $lt ':}}): Print (item)

Or a record that is greater than a value

For item in Db.col.find ({' age ': {' $gt ':}}): Print (item)

Statistics Query

The above code can count all the records.

Db.col.find (). Count ()//4

or add some conditions.

Db.col.find ({"Age": {"$GT": +}}). Count ()//2

Query records according to _ID

_ID is a MongoDB auto-generated ID whose type is objectid and needs to be converted to use.

This method is available in Python3, but you need to import a library.

From Bson.objectid import Objectid

This makes it possible to query directly using _ID.

Collection.find_one ({' _id ': ObjectId (' 592550e5d92fac0b8c449f87 ')})

Result sort

Just put the fields you want to sort into the sort method, and MongoDB defaults to ascending

Db.col.find (). Sort ("age")

But you can also add some parameters to change the way you sort. Like reverse, but remember to import the Pymongo library first.

Import Pymongodb.col.find (). Sort ("UserName", Pymongo. Descending)

You can also make him ascending, though by default this

For item in Db.col.find (). Sort (' age ', Pymongo. Ascending): Print (item)

Update data

Updating the data is simple and requires only one condition and data to be updated

Copy the Code code as follows:

Db.col.update ({' _id ': ObjectId (' 59255118d92fac43dcb1999a ')},{' $set ': {' name ': ' King di ma 33333 '}})

The results are as follows: Wang Yima became Wang Yima 33333

The code is as follows:

{' _id ': ObjectId (' 59255118d92fac43dcb1999a '), ' name ': ' Wang Yima 33333 ', ' Province ': ' Guangdong ', ' age ': 30}

Delete data

Delete data using the Remove () method, delete the specified condition data if the method is conditional, or delete all

Remove the name of the user who is Wang Ma er 33333.

Db.col.remove ({' name ': ' King bis hemp 33333 '})

Delete all data (with caution)

Db.col.remove ()
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.