mongodb回顾

mongodb是文档型数据库,使用BJSON(Binary JSON)格式存储数据,与JSON高度兼容


数据库(Database):存储数据的容器,类似关系型数据库的数据库

集合(Collection):数据库中的集合,相当于数据库中的表

文档(Document):数据记录,相当于关系型数据库中数据表的行(row),以BJSON格式存储


1.查看版本:db.version();

2.mongo --eval "db.version()" 或 mongod --version 或 systemctl status mongod

A:主版本号,重大更新时递增。B:次版本号,偶数为稳定版,奇数为开发版(如 4.4 为稳定版,4.5 为开发版)C:修订号,仅修复 bug,保持兼容性


标准连接库:mongodb://username:password@host1:port1,...hostN\[:portN]/\[defaultauthdb?options]

mongodb://:协议头,表示使用 MongoDB。

username:password@:(可选)认证信息,包括用户名和密码。

host1:port1,...hostN\[:portN]:服务器地址和端口,可以是一个或多个 MongoDB 服务器的地址和端口。

/defaultauthdb:(可选)默认认证数据库。

?options:(可选)连接选项。


标准的连接格式包含了多个选项(options),如下所示:

authSource:指定认证数据库。

replicaSet:指定副本集的名称。

ssl:启用 SSL 连接(true 或 false)。

readPreference:指定读偏好,如 primary, primaryPreferred, secondary, secondaryPreferred, nearest。

connectTimeoutMS:指定连接超时时间(毫秒)。

socketTimeoutMS:指定套接字超时时间(毫秒)

=====

连接到本地:mongodb://localhost

连接到本地指定数据库:mongodb://localhost/mydatabase

使用用户名和密码连接到本地 MongoDB 实例:mongodb://username:password@localhost/mydatabase

连接到远程 MongoDB 实例:mongodb://remotehost:27017

连接到副本集(Replica Set):mongodb://host1:27017,host2:27017,host3:27017/mydatabase?replicaSet=myReplicaSet

使用 SSL 连接到 MongoDB:

mongodb://username:password@localhost:27017/mydatabase?ssl=true

使用多个选项连接:

mongodb://username:password@localhost:27017/mydatabase?authSource=admin&ssl=true


###php连接:

require 'vendor/autoload.php'; // 引入 Composer 自动加载文件

$client = new MongoDB\Client("mongodb://localhost:27017"); // 连接到本地 MongoDB 实例

database = client->selectDatabase('mydatabase'); // 选择数据库

collection = database->selectCollection('mycollection'); // 选择集合

// 插入文档

result = collection->insertOne('name' =\> 'Alice', 'age' =\> 30);

echo "Inserted with Object ID '{$result->getInsertedId()}'";

// 查询文档

document = collection->findOne('name' =\> 'Alice');

echo "Found document: " . json_encode($document);

###java连接

import com.mongodb.client.MongoClient;

import com.mongodb.client.MongoClients;

import com.mongodb.client.MongoDatabase;

public class MongoDBConnection {

public static void main(String\[\] args) {

String uri = "mongodb://user:password@localhost:27017/mydatabase?authSource=admin";

try (MongoClient mongoClient = MongoClients.create(uri)) {

MongoDatabase database = mongoClient.getDatabase("mydatabase");

System.out.println("Connected to MongoDB");

}

}

}


{"name":"lisi","age":30,"address":{"city":"beijing","point":""}}

1.连接数据库:mongosh --host <hostname> --port <port>

2.切换数据库:use <database-name> (数据库未存在则建立此库)

===

show dbs;查看所有数据库

show collections; 查看数据库所有集合

use <database-name>切换不存在则创建

db.dropDatabase() #删除当前在使用的数据库

db.createCollection("dbTable",options)或开启验证

db.createCollection("dbTable", {

validator: {

age: { $gt: 0 }

}

});

db.dbTable.drop() #删除指定集合表

//更新集合名

db.adminCommand({

renameCollection: "sourceDb.sourceCollection",

to: "targetDb.targetCollection",

dropTarget: <boolean>

})

renameCollection:要重命名的集合的完全限定名称(包括数据库名)

to:目标集合的完全限定名称(包括数据库名)

dropTarget(可选):布尔值。如果目标集合已经存在,是否删除目标集合。默认值为 false

===

// 随时添加或删除表字段

db.collection.updateOne(

{ _id: 1 },

{ $set: { "newField": "value" } }

)

//支持复杂的聚合操作,如分组、排序

db.collection.aggregate([

{ match: { age: { gt: 25 } } },

{ group: { _id: "city", count: { $sum: 1 } } }

])

//

db.dbTable.insertOne({"name":"lisi","address":{"city":"beijing","info":"首都"}})

db.dbTable.find({"address.city":"beijing"}) //查询

db.dbTable.insertMany({},{},options)插入多个文档(options:ordered:false)

***ordered: false:表示无序插入,即使某个文档插入失败,也不会影响其他文档的插入

db.dbTable.insert({ name: "David"}或{ name: "David"},{ name: "David"},options)插入单个或多个(弃用)

db.dbTable.save({id: ObjectId("60c72b2f9b1d8b5a5f8e2b2d"),name: "David"},options)插入或更新(弃用)

//更新

1.db.collection.updateOne(filter, update, options)

*** filter:用于查找文档的查询条件。update:指定更新操作的文档或更新操作符。update:指定更新操作的文档或更新操作符

db.dbTable.updateOne(

{ name: "Alice" }, // 过滤条件

{ $set: { age: 26 } }, // 更新操作

{ upsert: false } // 可选参数

);

2.updateMany() 方法用于更新所有匹配过滤器的文档。

db.dbTable.updateMany(filter, update, options)

***filter:用于查找文档的查询条件。update:指定更新操作的文档或更新操作符options:可选参数对象,如 upsert、arrayFilters 等

db.dbTable.updateMany(

{ age: { $lt: 30 } }, // 过滤条件

{ $set: { status: "active" } }, // 更新操作

{ upsert: false } // 可选参数

);

3.replaceOne() 方法用于替换匹配过滤器的单个文档,新的文档将完全替换旧的文档。

db.dbTable.replaceOne(filter, replacement, options)

*** filter:用于查找文档的查询条件replacement:新的文档,将替换旧的文档options:可选参数对象,如 upsert 等。

db.myCollection.replaceOne(

{ name: "Bob" }, // 过滤条件

{ name: "Bob", age: 31 } // 新文档

);

4.findOneAndUpdate() 查找并更新单个文档,可以选择返回更新前或更新后的文档。

db.dbTable.findOneAndUpdate(filter, update, options)

*** filter:用于查找文档的查询条件。update:指定更新操作的文档或更新操作符options:可选参数对象,如 projection、sort、upsert、returnDocument 等

db.myCollection.findOneAndUpdate(

{ name: "Charlie" }, // 过滤条件

{ $set: { age: 36 } }, // 更新操作

{ returnDocument: "after" } // 可选参数,返回更新后的文档

);

***********

更新方法的 options 参数通常可以包含以下选项:

upsert:如果没有匹配的文档,是否插入一个新文档

arrayFilters:当更新嵌套数组时,指定应更新的数组元素的条件

collation:指定比较字符串时使用的排序规则

returnDocument:在 findOneAndUpdate 中使用,指定返回更新前 ("before") 或更新后 ("after") 的文档

**********

###删除文档

1.deleteOne() 方法用于删除匹配过滤器的单个文档

db.dbTable.deleteOne(filter, options)

***filter:用于查找要删除的文档的查询条件。options(可选):一个可选参数对象

db.myCollection.deleteOne({ name: "Alice" });

返回{

"acknowledged": true,

"deletedCount": 1

}

2.deleteMany() 方法用于删除所有匹配过滤器的文档。

db.collection.deleteMany(filter, options)

db.myCollection.deleteMany({ status: "inactive" });

3.findOneAndDelete() 方法用于查找并删除单个文档,并可以选择返回删除的文档。

db.collection.findOneAndDelete(filter, options)

**filter:用于查找要删除的文档的查询条件。options:可选参数对象,如 projection投影、sort 等。

db.myCollection.findOneAndDelete(

{ name: "Charlie" },

{ projection: { name: 1, age: 1 } }

);indOneAndDelete 返回被删除的文档,如果找不到匹配的文档,则返回 null

*****删除方法的 options 参数通常可以包含以下选项:

writeConcern:指定写操作的确认级别;collation:指定比较字符串时使用的排序规则;projection(仅适用于 findOneAndDelete):指定返回的字段;sort(仅适用于 findOneAndDelete):指定排序顺序以确定要删除的文档

###查询

*{ field1: 1, field2: -1 }:指定要排序的字段及排序顺序。1 表示升序,-1 表示降序。

db.collection.find().sort({ field1: 1, field2: -1 });

1.db.dbTable.find(query, projection).pretty()

**query:用于查找文档的查询条件。默认为 {},即匹配所有文档。projection(可选):指定返回结果中包含或排除的字段

*以易读的方式来读取数据,可以使用 pretty() 方法

2.findOne() 方法用于查找集合中的单个文档。如果找到多个匹配的文档,它只返回第一个。

db.collection.findOne(query, projection)

**query:用于查找文档的查询条件。默认为 {},即匹配所有文档; projection(可选):指定返回结果中包含或排除的字段

****高级查询******

2.1MongoDB 支持多种比较操作符,如 gt、lt、gte、lte、eq、ne in({"age":in:1,2}) nin(nin:1,2)等。

db.myCollection.find({ age: { $gt: 25 } });

2.2MongoDB 支持多种逻辑操作符,如 and、or、not、nor 等

***********

and 逻辑与,符合所有条件 { and: { age: { $gt: 25 } }, { city: "New York" } }

or 逻辑或,符合任意条件 { or: { age: { $lt: 25 } }, { city: "New York" } }

not 取反,不符合条件 { age: { not: { $gt: 25 } } }

nor 逻辑或非,均不符合条件 { nor: { age: { $gt: 25 } }, { city: "New York" } }

1.{ $and: { condition1 }, { condition2 } }

db.collection.find({ and: \[{ age: { gt: 25 } }, { age: { $lt: 35 } }] })

2.{ $or: { condition1 }, { condition2 } }

db.collection.find({ or: \[{ age: { gt: 25 } }, { age: { $lt: 18 } }] })

###元素操作符

{ field: { $exists: boolean } }

db.collection.find({ age: { $exists: true } })

{ field: { $type: "type" } }

db.collection.find({ age: { $type: "int" } })

###数组操作符

1.{ field: { $all: value1, value2, ... } }

查找 tags 数组中包含 "mongodb" 和 "database" 的文档

db.collection.find({ tags: { $all: "mongodb", "database" } })

2.$elemMatch (数组中至少有一个元素符合条件)

{ field: { $elemMatch: { condition } } }

db.collection.find({ items: { elemMatch: { quantity: { gt: 10 } } } })

3.$size (数组的大小)

{ field: { $size: value } }

db.collection.find({ tags: { $size: 3 } })

4.$regex (正则表达式匹配)

{ field: { $regex: "pattern" } }

查找 name 以 "John" 开头的文档:db.collection.find({ name: { $regex: /^John/ } })

5.$near (接近指定点的文档)

{ field: { near: \[longitude, latitude\], maxDistance: distance } }

查找距离某个位置近的文档:db.collection.find({ location: { near: \[10, 20\], maxDistance: 1000 } })

6.$geoWithin (查找指定区域内的文档)

{ field: { geoWithin: { centerSphere: \[longitude, latitude, radius] } } }

db.collection.find({ location: { geoWithin: { centerSphere: \[10, 20, 1] } } })

7.查找字段类型为字符串的文档:

db.myCollection.find({ fieldName: { $type: "string|2" } })

db.myCollection.find({ age: { $type: "int|16" } })

db.myCollection.find({ isActive: { $type: "bool|8" } })

db.myCollection.find({ createdAt: { $type: "date|9" } })

db.myCollection.find({ value: { $type: "string\|2", "int\|16" } })

类型代码 类型名称

1 double

2 string

3 object

4 array

5 binData

6 undefined

7 objectId

8 bool

9 date

10 null

11 regex

12 dbPointer

13 javascript

14 symbol

15 javascriptWithScope

16 int

17 timestamp

18 long

19 decimal

255 minKey

127 maxKey

***********

db.myCollection.find({

$and: [

{ age: { $gt: 25 } },

{ city: "New York" }

]

});

2.3使用正则表达式进行模式匹配查询。

db.myCollection.find({ name: /^A/ });

2.4投影用于控制查询结果中返回的字段。可以使用包含字段和排除字段两种方式

db.dbTable.find(

{ age: { $gt: 25 } },

{ name: 1, age: 1, _id: 0 }

);

2.5对查询结果进行排序-按年龄降序排序:

db.dbTable.find().sort({ age: -1 });

2.6对查询结果进行限制和跳过指定数量的文档

db.dbTable.find().limit(10);

跳过前 5 个文档,返回接下来的 10 个文档:

db.myCollection.find().skip(5).limit(10);

eg:

db.myCollection.find(

{

$and: [

{ age: { $gt: 25 } },

{ city: "New York" }

]

},

{ name: 1, age: 1, _id: 0 }

).sort({ age: -1 }).limit(10);

###创建索引

******************

注意在 3.0.0 版本前创建索引方法为 db.collection.ensureIndex(),之后的版本使用了 db.collection.createIndex() 方法,ensureIndex() 还能用,但只是 createIndex() 的别名。

db.collection.createIndex( keys, options )

db:数据库的引用。

collection:集合的名称。

keys:一个对象,指定了字段名和索引的排序方向(1 表示升序,-1 表示降序)。

options:一个可选参数,可以包含索引的额外选项。

options 参数是一个对象,可以包含多种配置选项,以下是一些常用的选项:

unique:如果设置为 true,则创建唯一索引,确保索引字段的值在集合中是唯一的。

background:如果设置为 true,则索引创建过程在后台运行,不影响其他数据库操作。

name:指定索引的名称,如果不指定,MongoDB 会根据索引的字段自动生成一个名称。

sparse:如果设置为 true,创建稀疏索引,只索引那些包含索引字段的文档。

expireAfterSeconds:设置索引字段的过期时间,MongoDB 将自动删除过期的文档。

v:索引版本,通常不需要手动设置。

weights:为文本索引指定权重。

// 创建 age 字段的升序索引

db.myCollection.createIndex({ age: 1 });

// 创建 name 字段的文本索引

db.myCollection.createIndex({ name: "text" });

// 创建唯一索引

db.collection.createIndex( { field: 1 }, { unique: true } )

// 创建后台运行的索引

db.collection.createIndex( { field: 1 }, { background: true } )

// 创建稀疏索引

db.collection.createIndex( { field: 1 }, { sparse: true } )

// 创建文本索引并指定权重

db.collection.createIndex( { field: "text" }, { weights: { field: 10 } } )

创建地理空间索引

对于存储地理位置数据的字段,可以使用 2dsphere 或 2d 索引类型来创建地理空间索引。

// 2dsphere 索引,适用于球形地理数据

db.collection.createIndex( { location: "2dsphere" } )

// 2d 索引,适用于平面地理数据

db.collection.createIndex( { location: "2d" } )

###查看索引

db.collection.getIndexes()

###删除索引

// 删除指定的索引

db.collection.dropIndex( "indexName" )

// 删除所有索引

db.collection.dropIndexes()

索引策略

在创建索引时,需要考虑以下因素:

查询频率:优先考虑那些经常用于查询的字段。

字段基数:字段值的基数越高(即唯一值越多),索引的效果越好。

索引大小:索引的大小会影响数据库的内存占用和查询性能。

索引优化

在对索引进行优化时,可以考虑以下方法:

选择合适的索引类型:根据查询需求选择合适的索引类型。

创建复合索引:对于经常一起使用的字段,考虑创建复合索引以提高查询效率。

监控索引性能:定期监控索引的使用情况,根据实际需求调整索引。

注意事项

索引虽然可以提高查询性能,但也会增加写操作的开销。因此,在创建索引时需要权衡查询性能和写入性能。

索引会占用额外的存储空间,特别是对于大型数据集,需要考虑索引的存储成本。

**************

===

3.创建用户:

db.createUser({

user: "testuser",

pwd: "password",

roles: [

{role:"readWrite",db:"<database-name>"},

{role:"dbAdmin",db:"<database-name>"}

]

})

4.验证用户

db.auth("usertest","password")

5.启用身份验证,编辑mogod.conf(安全访问MongoDB)

security:

authorization:"enabled"

*重启mongodb

6.使用用户身份登录

mongosh --host <hostname> --port <port:27017> -u "usertest" -p "password" --authenticationDatabase "<database-name>"

7.删除用户db.dropUser("usertest")

#########MongoDB副本集设置

现在我们通过指定 --replSet 选项来启动mongoDB。--replSet 基本语法格式如下:

mongod --port "PORT" --dbpath "YOUR_DB_DATA_PATH" --replSet "REPLICA_SET_INSTANCE_NAME"

实例:mongod --port 27017 --dbpath "D:\set up\mongodb\data" --replSet rs0

或:

添加副本集的成员,我们需要使用多台服务器来启动mongo服务。进入Mongo客户端,并使用rs.add()方法来添加副本集的成员rs.add() 命令基本语法格式如下:

>rs.add(HOST_NAME:PORT)

*MongoDB中你只能通过主节点将Mongo服务添加到副本集中, 判断当前运行的Mongo服务是否为主节点可以使用命令db.isMaster() 。

安装:

$ wget http://pecl.php.net/get/mongodb-1.5.2.tgz

$ cd /mongodb-1.5.2

$ phpize

$ ./configure

$ make && make install

或php自己编译的,则安装方法如下(假设是编译在 /usr/local/php目录中):

$ wget http://pecl.php.net/get/mongodb-1.5.2.tgz

$ cd /mongodb-1.5.2

$ /usr/local/php/bin/phpize

$ ./configure --with-php-config=/usr/local/php/bin/php-config

$ make && make install

安装成功后:installing shared extensions: /usr/lib/php/extensions/debug-non-zts-20151012/

在php.ini添加:

extension_dir=/usr/lib/php/extensions/debug-non-zts-20151012/

extension=mongodb.so

* extension_dir 配置项的路径:php -i | grep extension_dir

php代码:

$m = new MongoClient(); // 连接

db = m->test; // 获取名称为 "test" 的数据库

collection = db->createCollection("testdb");

echo "集合创建成功";

collection = db->testdb; // 选择集合

插入数据:

$document = array(

"title" => "MongoDB",

"description" => "database",

"likes" => 100,

"url" => "http://www.runoob.com/mongodb/",

"by", "菜鸟教程"

);

collection-\>insert(document);

echo "数据插入成功";

cursor = collection->find();

// 迭代显示文档标题

foreach (cursor as document) {

echo $document"title" . "\n";

}

更新数据

collection-\>update(array("title"=\>"MongoDB"), array('set'=>array("title"=>"MongoDB 教程")));

// 显示更新后的文档

cursor = collection->find();

// 循环显示文档标题

foreach (cursor as document) {

echo $document"title" . "\n";

}

删除数据

// 移除文档

$collection->remove(array("title"=>"MongoDB 教程"), array("justOne" => true));

// 显示可用文档数据

cursor = collection->find();

foreach (cursor as document) {

echo $document"title" . "\n";

}

在php中还可以使用findOne(), save(), limit(), skip(), sort()等方法来操作Mongodb数据库

相关推荐
葫芦和十三4 小时前
图解 MongoDB 22|读写关注:持久性与一致性的档位选择
后端·mongodb·agent
葫芦和十三11 小时前
图解 MongoDB 21|选举与 failover:Primary 是怎么选出来的
后端·mongodb·agent
jiayou641 天前
KingbaseES 表级与列级加密完全指南
数据库·后端
葫芦和十三2 天前
图解 MongoDB 19|Oplog:复制的真正载体,不是文档是操作
后端·mongodb·agent
葫芦和十三2 天前
图解 MongoDB 20|复制延迟与 catch up:Secondary 为什么跟不上
后端·mongodb·agent
GBASE2 天前
G术时刻 |GBase 8s数据库事务并发控制之封锁技术介绍(下)
数据库
xiezhr2 天前
逛GitHub发现了一款免费的带AI功能的数据库管理工具
数据库·ai编程·dba
吃糖的小孩3 天前
给 QQ AI 机器人设计“可控记忆”:会话摘要、手动长期记忆与角色卡边界
数据库
葫芦和十三3 天前
图解 MongoDB 17|大集合与工作集:数据超过内存怎么办
后端·mongodb·面试
葫芦和十三3 天前
图解 MongoDB 18|复制集拓扑:Primary、Secondary 和 Arbiter 的分工
后端·mongodb·面试