search
HomeDatabaseMysql Tutorial非关系型数据库mongodb入门(一步一步 版)

本文主要内容: 1.简要介绍mongodb 2.Pymongo 3.mongo shell 4.我的mongodb入门之旅 1.简要介绍mongodb MongoDB是一个基于分布式文件存储的数据库。由C++语言编写。旨在为WEB应用提供可扩展的高性能数据存储解决方案。MongoDB是一个介于关系数据库和非关系数

本文主要内容:

1.简要介绍mongodb

2.Pymongo

3.mongo shell

4.我的mongodb入门之旅

1.简要介绍mongodb

MongoDB是一个基于分布式文件存储的数据库。由C++语言编写。旨在为WEB应用提供可扩展的高性能数据存储解决方案。MongoDB是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。他支持的数据结构非常松散,是类似json的bjson格式,因此可以存储比较复杂的数据类型。Mongo最大的特点是他支持的查询语言非常强大,其语法有点类似于面向对象的查询语言,几乎可以实现类似关系数据库单表查询的绝大部分功能,而且还支持对数据建立索引。园里有博友的介绍写的比较详细,还介绍了mongo的安装

2.Pymongo

在说pymongo之前,先看看一篇博文,特别适合有数据库操作经验的看:

PyMongo 是 MongoDB 的 Python 接口开发包。

3.mongo shell

学mongo非常有必要学mongo shell

因为mongo shell 可以更加便捷的直接操作数据库,特别适合检查。

这里园里有一篇总结的挺好:

这个shell和Mongodb里的很多操作都有相似之处,不要孤立起来学

4.我的mongodb入门之旅

以上这些信息,我们不可能一开始就掌握,稍微有个大致的了解就行。

OK,下面开始我的mongo入门之旅了,香港服务器租用,这才是今天的重点

4.1  使用 mongo -port XXXX 登录shell (由于服务器中的mongo端口已经更改了)

4.2  use test_for_new (建立一个新的数据库,我在shell里没找到建立的命令,试了下这个use命令,这个也能间接建立数据库)

4.3  show dbs 显示系统的数据库名称 和对应大小

     show collections 显示当前使用的数据库中的collections(应该是集合的意思),这个collection对应于关系数据库中表。show tables 有同样效果

     db 查看当前使用数据库的名称

4.4  同样没找到建立collections的现成命令,实验后发现。这个数据库的使用就和python里的变量一样不需事先申明。

     直接用就行了,没有的话会自动建立。可以用dbs.collections的形式(像面向对象吧),例如:

     db.collection1.insert({a:1,b:1}) 怎一个爽字了得,服务器空间,这个{}可以理解成python里的dict。还有如果嫌命令太长,可以事先将

     coll=db.collection1 (赋值给一个临时变量) coll.insert({a:1,b:1}) 这插入格式为什么是这样,先放放 咱不急。

     使用coll.find()就可以看到collection1的所有数据了,使用coll.drop()就可以删除该collection及里面的数据了。那么多插一些数据到collection1吧

4.5  关于插入,必须要注意几点。其一,因为是非关系的,所以不会严格限制格式,底层的存储像dict 所以可以 coll.insert({a:1,b:1,c:1})

     其二,即便你再coll.insert({a:1,b:1})一下,他也不会报错,香港服务器,而且出来的是两条该数据,不信的话用coll.find({a:1,b:1})试试

     事实上系统会增加一个唯一标识字段“_id”用于区分数据

    这点和versant数据库到很像,有点面向对象的味道

4.6       删除a=1,b=1的数据

    coll.remove({a:1,b:1}) 注意了 删的是俩条数据哦

4.7  将b=1的所有数据的a改成1

     coll.update({b:1},{$set:{a:1}})

4.8      OK,增删改查都有了 shell差不多就介绍这么多了。下面要用pymongo

    关于pymongo的介绍,我想没必要再这样一步一步来了,否则就有污蔑大众智商的嫌疑了。直接给代码吧,我尽量多写些有意义的注释。

pymongo PyConnect(object): (self, host, port): : 10 self.conn = pymongo.Connection(host, port) 11 except Error: %(host, port) 13 exit(0) (self): 16 self.conn.close() use(self, dbname): self.db = self.conn[dbname] setCollection(self, collection): self.db: exit(0) 27 else: 28 self.coll = self.db[collection] find(self, query = {}): type(query) is not dict: exit(0) 35 try: self.coll: : 40 result = self.coll.find(query) 41 except NameError: ,query 43 exit(0) 44 return result insert(self, data): dict: exit(0) self.coll.insert(data) remove(self, data): dict: exit(0) self.coll.remove(data) update(self, data, setdata): dict or type(setdata) is not dict: exit(0) self.coll.update(data,{:setdata}) == : , 27017) ) ) :10, :1}) 72 result = connect.find() :10, :1}, {:10}) x in result: x: ], x[], x[], x[] 78 else: ], x[], x[] :10})

4.9  补充:在调用self.conn[dbname]和self.db[collection].find(query)的时候要是能再加个存在性判断就好了,不然很容易出问题。

5.0  好了,本文到这里就结束了,最后留个问题。在以上代码中最终输出结果里为什么是a=10,b=10,而不是a=10,b=1

 

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What Are the Limitations of Using Views in MySQL?What Are the Limitations of Using Views in MySQL?May 14, 2025 am 12:10 AM

MySQLviewshavelimitations:1)Theydon'tsupportallSQLoperations,restrictingdatamanipulationthroughviewswithjoinsorsubqueries.2)Theycanimpactperformance,especiallywithcomplexqueriesorlargedatasets.3)Viewsdon'tstoredata,potentiallyleadingtooutdatedinforma

Securing Your MySQL Database: Adding Users and Granting PrivilegesSecuring Your MySQL Database: Adding Users and Granting PrivilegesMay 14, 2025 am 12:09 AM

ProperusermanagementinMySQLiscrucialforenhancingsecurityandensuringefficientdatabaseoperation.1)UseCREATEUSERtoaddusers,specifyingconnectionsourcewith@'localhost'or@'%'.2)GrantspecificprivilegeswithGRANT,usingleastprivilegeprincipletominimizerisks.3)

What Factors Influence the Number of Triggers I Can Use in MySQL?What Factors Influence the Number of Triggers I Can Use in MySQL?May 14, 2025 am 12:08 AM

MySQLdoesn'timposeahardlimitontriggers,butpracticalfactorsdeterminetheireffectiveuse:1)Serverconfigurationimpactstriggermanagement;2)Complextriggersincreasesystemload;3)Largertablesslowtriggerperformance;4)Highconcurrencycancausetriggercontention;5)M

MySQL: Is it safe to store BLOB?MySQL: Is it safe to store BLOB?May 14, 2025 am 12:07 AM

Yes,it'ssafetostoreBLOBdatainMySQL,butconsiderthesefactors:1)StorageSpace:BLOBscanconsumesignificantspace,potentiallyincreasingcostsandslowingperformance.2)Performance:LargerrowsizesduetoBLOBsmayslowdownqueries.3)BackupandRecovery:Theseprocessescanbe

MySQL: Adding a user through a PHP web interfaceMySQL: Adding a user through a PHP web interfaceMay 14, 2025 am 12:04 AM

Adding MySQL users through the PHP web interface can use MySQLi extensions. The steps are as follows: 1. Connect to the MySQL database and use the MySQLi extension. 2. Create a user, use the CREATEUSER statement, and use the PASSWORD() function to encrypt the password. 3. Prevent SQL injection and use the mysqli_real_escape_string() function to process user input. 4. Assign permissions to new users and use the GRANT statement.

MySQL: BLOB and other no-sql storage, what are the differences?MySQL: BLOB and other no-sql storage, what are the differences?May 13, 2025 am 12:14 AM

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

MySQL Add User: Syntax, Options, and Security Best PracticesMySQL Add User: Syntax, Options, and Security Best PracticesMay 13, 2025 am 12:12 AM

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

MySQL: How to avoid String Data Types common mistakes?MySQL: How to avoid String Data Types common mistakes?May 13, 2025 am 12:09 AM

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)