Operations and Learning Python Reptile Intermediate (eight) MongoDB

Source: Internet
Author: User
Tags bulk insert create mongodb db2 db2 client install mongodb mongoclient mongodb server mongo shell


1 MongoDB


MongoDB is written by the C + + language and is an open source database system based on distributed file storage. With high performance, high availability, and automatic scalability. MongoDB stores data as a document and data structures consist of key-value (key=>value) pairs. The MongoDB document is similar to the Bson of a JSON object. Field values can contain other documents, arrays, and array of documents. The biggest feature of MongoDB is that the query language he supports is very powerful, its syntax is a bit like object-oriented query language, almost can realize the most functions like relational database single table query, but also support the index of data.


1.1 Installing MongoDB


MongoDB supports a variety of installation methods specific installation can crossing network more installation methods, I here only briefly introduce the source package to install MongoDB Community Edition.


# Download the source package
curl -O https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-3.6.2.tgz
# Extract to local
tar -zxvf mongodb-linux-x86_64-3.6.2.tgz
# Create mongodb directory
mkdir -p / usr / local / mongodb
# Copy to the directory you just created
cp -R -n mongodb-linux-x86_64-3.6.2 / / usr / local / mongodb
# Define environment variables, add mongodb bin directory to it
export PATH = <mongodb-install-directory> / bin: $ PATH
# Create a data directory, the default is / data / db, if your directory is not here, you can specify it with the --dbpath parameter
mkdir -p / data / db


The installation is complete, so simple.


1.2 Conceptual analysis


The following table shows the various SQL terms and concepts, along with the corresponding MongoDB terminology and concepts.


SQL MongoDB explain
Database Database Database
Table Collection Database Tables/Collections
Row Document or BSON document Data record lines/documents
Column Field Data fields/Fields
Index Index Index
Table joins $lookup, embedded documents Table Connection
Primary key Primary key Specify any unique column or column group to co-operate as the primary key/in MongoDB, the main key is automatically set to the _id field.


The following table shows some database executables and the corresponding MongoDB executables, noting that the table is not all listed.


server/client MongoDB MySQL Oracle Informix DB2
Database Server mongod mysqld Oracle IDS DB2 Server
Database Client MONGO mysql sqlplus db-access DB2 Client


As you can see from the chart above, the concept of collection (collection) and document documents is introduced in MongoDB, which is different from the relational database.
Document
Document is the basic unit of data in MongoDB, is the core concept of MongoDB, very similar to the relational database of Rows (records) collection can be seen as a non-modal table (table)
Collection (collection)
Represents a set of MongoDB documents. A collection is equivalent to an RDBMS table. A collection exists in a database. The collection does not have a mandatory pattern, and the documents in a collection can have different fields. In general, all documents in a collection have similar or related purposes.
Database
More than one document in MongoDB forms a collection, and multiple collections form a database. The physical container used for the collection. Each database has its own set of files on the file system. A MONGODB server typically has multiple databases.
MONGO Shell
is an interactive JavaScript interface for MongoDB. You can use the MONGO Shell to query and update data and perform administrative actions.
You can see the concepts above:


2 Integration with Python 2.1 installation Pymongo


Pymongo is a python driver for MongoDB, do not install a third-party "Bson" package that is incompatible with Pymongo. Pymongo has its own Bson software package;


# Run the python -m pip install pymongo command to install, the results are as follows:
(myenv) [[email protected] myenv] $ python -m pip install pymongo
Collecting pymongo
   Downloading pymongo-3.6.0-cp34-cp34m-manylinux1_x86_64.whl (379kB)
     100% | ████████████████████████████████ | 389kB 73kB / s
Installing collected packages: pymongo
Successfully installed pymongo-3.6.0


After the installation is complete, execute the Import module command to see if it is successful:




Note: To make sure that MongoDB is installed on your machine.


2.2 Establishing connections and operations
# Import the client module
>>> from pymongo import MongoClient
# Create a client instance
>>> client = MongoClient ()
# This method is the same as above. Without parameters, the default connection is localhost and port 27017.
>>> client = MongoClient (‘localhost‘, 27017)
# You can also connect by URI
>>> client = MongoClient (‘mongodb: // localhost: 27017 /’)


Get database
Accessing the database using the property styles in the client instance


>>> db = client.test_database


If the database name is such a ' test-database ', then using the property style access will not work, then you can use the dictionary style to access


>>>db = client[‘test-database‘]


Get Collection (collection)


>>> collection = db.test_collection


or (using dictionary-style access):


collection = db[‘test-collection‘]


Document
Data in MongoDB is represented (and stored) using a JSON-styled document. In Pymongo, we use a dictionary to represent the document. For example, the following dictionary may be used to represent a blog post:


import datetime
from pymongo import MongoClient
client = MongoClient()

post = {"author": "Mike",
         "text": "My first blog post!",
         "tags": ["mongodb", "python", "pymongo"],
         "date": datetime.datetime.utcnow()}


Insert Document
Insert a single document
To insert a document into the collection, you can use the Insert_one () method:


#!/usr/bin/python3
#coding=utf-8

import datetime
from pymongo import MongoClient
client = MongoClient()

db = client.pythondb

post = {"author": "Maxsu",
         "text": "My first blog post!",
         "tags": ["mongodb", "python", "pymongo"],
         "date": datetime.datetime.utcnow()}

posts = db.posts
post_id = posts.insert_one(post).inserted_id
print ("post id is ", post_id)


BULK INSERT
Pass a list as the first parameter to Insert_many () to perform a bulk insert operation


#!/usr/bin/python3
#coding=utf-8

import datetime
import pprint
from pymongo import MongoClient

client = MongoClient()

db = client.pythondb

new_posts = [{"_id": 1000,
               "author": "Curry",
               "text": "Another post!",
               "tags": ["bulk", "insert"],
               "date": datetime.datetime(2017, 11, 12, 11, 14)},
              {"_id": 1001,"author": "Maxsu",
               "title": "MongoDB is fun",
               "text": "and pretty easy too!",
               "date": datetime.datetime(2019, 11, 10, 10, 45)}]

posts = db.posts
result = posts.insert_many(new_posts)
print("Bulk Inserts Result is :", result.inserted_ids)
#print (post)


Inquire
Single Document Query
Get a single document using Find_one ()


#!/usr/bin/python3
#coding=utf-8

import datetime
from pymongo import MongoClient

client = MongoClient()

db = client.pythondb
post = {"author": "Minsu",
         "text": "This blog post belong to Minsu!",
         "tags": ["MySQL", "Oracle", "pymongo"],
         "date": datetime.datetime.utcnow()}

posts = db.posts
post_id = posts.insert_one(post).inserted_id

post = posts.find_one({"author": "Maxsu"})
print(post)
#print (post)


Querying multiple documents
You can use the Find () method, and find () returns a cursor instance that iterates through the returned results.


#!/usr/bin/python3
#coding=utf-8

from pymongo import MongoClient

client = MongoClient()

db = client.pythondb

posts = db.posts
for post in posts.find():
print(post)


MongoDB on the simple introduction here, the details of MongoDB content can refer to the official website



Part of this article reference: http://www.yiibai.com/mongodb/mongodb_python.html



Operations and Learning Python Reptile Intermediate (eight) 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.