MongoDB

MongoDB 是一个基于分布式文件存储的数据库。由 C++ 语言编写。旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。


概述

MongoDB 将数据存储为一个文档,数据结构由键值(key=>value)对组成。MongoDB 文档类似于 JSON 对象。字段值可以包含其他文档,数组及文档数组。

借助基于领先的现代数据库构建的应用程序数据平台,更快地将您的想法推向市场。支持事务性、搜索、分析和移动使用案例,同时采用通用查询接口和开发人员喜爱的数据模型。

MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。

主要特点

  • MongoDB 是一个面向文档存储的数据库,操作起来比较简单和容易。
  • 你可以在 MongoDB 记录中设置任何属性的索引 (如:FirstName="Sameer",Address="8 Gandhi Road")来实现更快的排序。
  • 你可以通过本地或者网络创建数据镜像,这使得 MongoDB 有更强的扩展性。
  • 如果负载的增加(需要更多的存储空间和更强的处理能力) ,它可以分布在计算机网络中的其他节点上这就是所谓的分片。
  • Mongo 支持丰富的查询表达式。查询指令使用 JSON 形式的标记,可轻易查询文档中内嵌的对象及数组。
  • MongoDB 使用 update() 命令可以实现替换完成的文档(数据)或者一些指定的数据字段 。
  • MongoDB 中的 Map/reduce 主要是用来对数据进行批量处理和聚合操作。
  • Map 和 Reduce。Map 函数调用 emit(key,value) 遍历集合中所有的记录,将 key 与 value 传给 Reduce 函数进行处理。
  • Map 函数和 Reduce 函数是使用 Javascript 编写的,并可以通过 db.runCommand 或 mapreduce 命令来执行MapReduce 操作。
  • GridFS 是 MongoDB 中的一个内置功能,可以用于存放大量小文件。
  • MongoDB 允许在服务端执行脚本,可以用 Javascript 编写某个函数,直接在服务端执行,也可以把函数的定义存储在服务端,下次直接调用即可。
  • MongoDB 支持各种编程语言:RUBY,PYTHON,JAVA,C++,PHP,C# 等多种语言。
  • MongoDB 安装简单。

安装

mongo 服务是由命令 /usr/bin/mongod --config /etc/mongod.conf 运行起来的,配置文件类似:

# mongod.conf

# for documentation of all options, see:
#   http://docs.mongodb.org/manual/reference/configuration-options/

# Where and how to store data.
storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true
#  engine:
#  wiredTiger:

# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

# network interfaces
net:
  port: 27017
  bindIp: 0.0.0.0


# how the process runs
processManagement:
  timeZoneInfo: /usr/share/zoneinfo

#security:

#operationProfiling:

#replication:
#replication:
#   replSetName: "rs0"

#sharding:

## Enterprise-Only Options:

#auditLog:

#snmp:

MongoDB Shell

$ ./mongo
MongoDB shell version v5.0.19
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("f99979bb-e568-4df7-9ac6-a51d8bb333f7") }
MongoDB server version: 5.0.19
> help
        db.help()                    help on db methods
        db.mycoll.help()             help on collection methods
        sh.help()                    sharding helpers
        rs.help()                    replica set helpers
        help admin                   administrative help
        help connect                 connecting to a db help
        help keys                    key shortcuts
        help misc                    misc things to know
        help mr                      mapreduce

        show dbs                     show database names
        show collections             show collections in current database
        show users                   show users in current database
        show profile                 show most recent system.profile entries with time >= 1ms
        show logs                    show the accessible logger names
        show log [name]              prints out the last segment of log in memory, 'global' is default
        use <db_name>                set current database
        db.mycoll.find()             list objects in collection mycoll
        db.mycoll.find( { a : 1 } )  list objects in mycoll where a == 1
        it                           result of the last line evaluated; use to further iterate
        DBQuery.shellBatchSize = x   set default number of items to display on shell
        exit                         quit the mongo shell
> show dbs
admin         0.000GB
config        0.000GB
identifier    0.030GB
local         0.032GB
test          0.001GB
teuringcloud  0.001GB
> use local
switched to db local
> db
local
> use test
switched to db test
> db
test
> 
# 如果数据库不存在,则创建数据库,否则切换到指定数据库。
> use jerry
switched to db jerry
> db
jerry
> show dbs
admin         0.000GB
config        0.000GB
identifier    0.030GB
local         0.032GB
test          0.001GB
teuringcloud  0.001GB
# 刚创建的数据库并不在数据库的列表中,要显示它,我们需要向数据库插入一些数据。
> db.jerry.insertOne({"name":"jerry"})
{
        "acknowledged" : true,
        "insertedId" : ObjectId("65684b758eebf50ac410488a")
}
> 
> show dbs
admin         0.000GB
config        0.000GB
identifier    0.030GB
jerry         0.000GB
local         0.032GB
test          0.001GB
teuringcloud  0.001GB
> db.jerry.find()
{ "_id" : ObjectId("65684b758eebf50ac410488a"), "name" : "jerry" }
# 删除数据库
> db.dropDatabase()
{ "ok" : 1 }
> show dbs
admin         0.000GB
config        0.000GB
identifier    0.030GB
local         0.032GB
test          0.001GB
teuringcloud  0.001GB
> use jerry
switched to db jerry
> db.createCollection("device")
{ "ok" : 1 }
> show dbs
admin         0.000GB
config        0.000GB
identifier    0.030GB
jerry         0.000GB
local         0.032GB
test          0.001GB
teuringcloud  0.001GB
> show tables
device
> 
> db.device.insert({"_id":"123456789","name":"jerry","create_time": new Date()})
WriteResult({ "nInserted" : 1 })
> 
> db.device.find().pretty()
{
        "_id" : "123456789",
        "name" : "jerry",
        "create_time" : ISODate("2023-12-01T08:33:38.837Z")
}
> 
> db.device.update({"_id":"123456789"},{$set:{"name":"DESKTOP-TMLEIUE"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> 
> db.device.find().pretty()
{
        "_id" : "123456789",
        "name" : "DESKTOP-TMLEIUE",
        "create_time" : ISODate("2023-12-01T08:35:38.279Z")
}
> 
> db.device.remove({"_id":"123456789"})
WriteResult({ "nRemoved" : 1 })
> 

参考资料