介绍

sql mongo
database database
table collection
row document
column field
index index
join
primary key primary key

安装

Docker

  1. docker run -d -p 27017:27017 \
  2. -e TZ=Asia/Beijing \
  3. -v /mongo:/data \
  4. --name mongo \
  5. mongo:latest

单机

  • 下载mongo-5.0.1上传至服务器/usr/local/目录下,并解压,然后重命名为mongo-5.0.1

    1. cd /usr/local
    2. tar -zxvf mongodb-linux-x86_64-rhel70-5.0.1.tgz
    3. mv mongodb-linux-x86_64-rhel70-5.0.1 mongo-5.0.1
  • 在解压目录中的bin目录下新建data、log文件夹

    1. cd ./mongo-5.0.1/bin/
    2. mkdir data log
  • 继续在该目录下创建mongo.conf配置文件,并编写相关配置

    1. vi /usr/local/mongo-5.0.1/bin/mongo.conf
    1. systemLog:
    2. destination: file
    3. logAppend: true
    4. # 日志文件存储路径
    5. path: /usr/local/mongo-5.0.1/bin/log/mongod.log
    6. storage:
    7. # 数据存储位置
    8. dbPath: /usr/local/mongo-5.0.1/bin/data
    9. journal:
    10. enabled: true
    11. processManagement:
    12. # 后台运行
    13. fork: true
    14. # 要事先创建/var/run/mongo文件夹
    15. pidFilePath: /var/run/mongo/mongod.pid
    16. timeZoneInfo: /usr/share/zoneinfo
    17. net:
    18. port: 27017
    19. # 允许任何ip访问
    20. bindIp: 0.0.0.0
    21. security:
    22. # 用户授权默认关闭
    23. authorization: disabled
  • 基于配置文件启动mongo服务实例 ```bash ./mongod -f ./mongo.conf

    或者用这个

    ./mongod —config ./mongo.conf

安全关闭

./mongod —shutdown -f ./mongo.conf

  1. - 如果不用配置,直接使用指令启动也是可以的
  2. ```bash
  3. # 如果开启权限需加上 --auth 参数
  4. ./mongod --bind_ip 0.0.0.0 --port 27017 --fork \
  5. --dbpath /usr/local/mongo-5.0.1/bin/data \
  6. --logpath /usr/local/mongo-5.0.1/bin/log/mongod.log \
  7. # 安全关闭
  8. ./mongod shutdown --bind_ip 0.0.0.0 --port 27017 --fork \
  9. --dbpath /usr/local/mongo-5.0.1/bin/data \
  10. --logpath /usr/local/mongo-5.0.1/bin/log/mongod.log \
  • 开启远程访问权限
    1. # 开放防火墙端口,重启,查看开放端口
    2. sudo firewall-cmd --zone=public --add-port=27017/tcp --permanent
    3. sudo firewall-cmd --reload
    4. sudo firewall-cmd --list-ports

    用户授权:MongoDB用户权限管理

复制集

副本集介绍

image.png
副本集:MongoDB副本集是将数据同步在多个服务器的过程,复制提供了数据的冗余备份,并在多个服务器上存储数据副本,提高了数据的可用性, 并可以保证数据的安全性,同时还允许从硬件故障和服务中断中恢复数据。
Oplog:Oplog是MongoDB Primary(主节点)和Secondary(从节点)在副本集建立期间和建立完成之后的复制介质。Primary中所有的写入操作都会记录到Oplog中,然后从节点会来主节点拉取Oplog并应用到自己的节点上。这里的Oplog是MongoDB local数据库的一个集合,它是Capped collection,通俗意思就是它是固定大小,循环使用的。
使用场景:

  • 数据冗余,用做故障恢复使用,当发生硬件故障或者其它原因造成的宕机时,可以使用副本进行恢复。
  • 读写分离,读的请求分流到副本上,减轻主节点的读压力。

副本集的原理:
image.png
集群中的各节点还会通过传递心跳信息来检测各自的健康状况。当主节点故障时,多个从节点会触发一次新的选举操作,并选举其中的一个成为新的主节点(通常谁的优先级更高,谁就是新的主节点),心跳信息默认每2秒传递一次。
image.png
客户端连接到副本集后,不关心具体哪一台机器是否挂掉。主服务器负责整个副本集的读写,副本集定期同步数据备份。一旦主节点挂掉,副本节点就会选举一个新的主服务器。这一切对于应用服务器不需要关心。
副本集中的副本节点在主节点挂掉后通过心跳机制检测到后,就会在集群内发起主节点的选举机制,自动选举出一位新的主服务器。

副本集角色

主节点(Primary):接收所有的写请求,然后把修改同步到所有Secondary。一个Replica Set只能有一个Primary节点,当Primary挂掉后,其他Secondary或者Arbiter节点会重新选举出来一个主节点。 默认读请求也是发到Primary节点处理的,可以通过修改客户端连接配置以支持读取 Secondary节点。
副本节点(Secondary):与主节点保持同样的数据集。当主节点挂掉的时候,参与选主。
仲裁者(Arbiter):不保存数据,不参与选主,只进行选主投票。使用Arbiter可以减轻数据存储的 硬件需求,Arbiter几乎没什么大的硬件资源需求,但重要的一点是,在生产环境下它和其他数据节点不要部署在同一台机器上。

两种架构模式

image.png
PSS:Primary + Secondary + Secondary模式,通过Primary和Secondary搭建的Replica Set。该模式下Replica Set节点数必须为奇数,目的是选主投票的时候要出现大多数(过半)才能进行选主决策。
image.png
PSA:Primary + Secondary + Arbiter模式,使用Arbiter搭建Replica Set。偶数个数据节点,加一个Arbiter构成的Replica Set。

选举机制

复制集通过replSetInitiate命令或rs.initiate()命令进行初始化。 初始化后各个成员间开始发送心跳消息,并发起Primary选举操作,获得大多数成员投票支持的节点,会成为Primary,其余节点成为Secondary。

大多数: 假设复制集内投票成员数量为N,则大多数为N/2 + 1,当复制集内存活成员数量不足大多数时,整个复制集将无法选举出Primary,复制集将无法提供写服务,处于只读状态。 关于大多数的计算如下表所示:

投票成员数 大多数 容忍失效数
1 1 0
2 2 0
3 2 1
4 3 1
5 3 2

Mongodb副本集的选举基于Bully算法,这是一种协调者竞选算法Primary的选举受节点间心跳、优先级、最新的oplog时间等多种因素影响。

特殊角色
Arbiter:Arbiter节点只参与投票,不能被选为 Primary,并且不从Primary同步数据。 当节点宕机导致复制集无法选出Primary时,可以给复制集添加一个Arbiter节点,即使有节点宕机,仍能选出Primary。Arbiter 本身不存储数据,是非常轻量级的服务,当复制集成员为偶数时,最好加入一个 Arbiter 节点,以提升复制集可用性。
Priority0:Priority0节点的选举优先级为0,不会被选举为Primary。 比如你跨机房A、B 部署了一个复制集,并且想指定Primary必须在A机房,这时可以将B机房的复制集成员Priorit 设置为0,这样Primary就一定会是A机房的成员。(注意:如果这样部署,最好将大多数节点部署在 A 机房, 否则网络分区时可能无法选出 Primary)。
Vote0:Mongodb 3.0里,复制集成员最多50个,参与Primary选举投票的成员最多7个,其他成员(Vote0)的 vote属性必须设置为0,即不参与投票。
Hidden:Hidden节点不能被选为主(Priority 为0),并且对Driver不可见。 因Hidden节点不会接受Driver的请求,可使用Hidden节点做一些数据备份、离线计算的任务,不会影响复制集的服务。
Delayed:Delayed节点必须是Hidden节点,并且其数据落后与Primary一段时间(可配置,比如1个 小时)。因 Delayed节点的数据比Primary落后一段时间,当错误或者无效的数据写入Primary时,可通过Delayed节点的数据来恢复到之前的时间点。

触发选举条件

  • 初始化一个副本集时。
  • 从库不能连接到主库(默认超过10s,可通过heartbeatTimeoutSecs参数控)),由从库发起选举。
  • 主库放弃Primary角色,比如执行rs.shutdown命令。

故障转移
image.png
Mongodb副本集通过心跳检测实现自动failover机制,进而实现高可用。

数据同步

Primary与Secondary之间通过oplog来同步数据,Primary 上的写操作完成后,会向特殊的local.oplog.rs特殊集合写入一条oplog,Secondary不断的从Primary取新的oplog并应用。 因oplog的数据会不断增加,local.oplog.rs被设置成为一个capped集合,当容量达到配置上限时,会将最旧的数据删除掉。

Secondary初次同步数据时,会先执行init sync,从Primary(或其他数据更新的Secondary)同步全量数据, 然后不断通过执行tailable cursor从Primary的local.oplog.rs集合里查询最新的oplog并应用到自身。考虑到oplog在Secondary上可能重复应用,oplog必须具有幂等性,即重复应用也会得到相同的结果。即将oplog的同一个操作执行多次,与执行一次的效果是一样的。简单的说就是:

当Primary节点完成数据操作后,Secondary会做出一系列的动作保证数据的同步:

  1. 检查自己local库的oplog.rs集合找出最近的时间戳。
  2. 检查Primary节点local库oplog.rs集合,找出大于此时间戳的记录。
  3. 将找到的记录插入到自己的oplog.rs集合中,并执行这些操作。

异常回滚
当Primary宕机时,如果有数据未同步到Secondary,当Primary重新加入时,如果新的Primary上已经发生了写操作,则旧Primary需要回滚部分操作,以保证数据集与新的Primary一致。 旧Primary将回滚的数据写到单独的rollback目录下,数据库管理员可根据需要使用mongorestore进行恢复。

读写配置

Read Preference默认情况下,复制集的所有读请求都发到Primary,Driver可通过设置Read Preference来将读请求路由到其他的节点。

  • primary:默认规则,所有读请求发到Primary;
  • primaryPreferred:Primary优先,如果Primary不可达,请求Secondary;
  • secondary:所有的读请求都发到Secondary;
  • secondaryPreferred:Secondary优先,当所有Secondary不可达时,请求Primary;
  • nearest:读请求发送到最近的可达节点上(通过ping探测得出最近的节点)。

Write Concern默认情况下,Primary 完成写操作即返回,Driver 可通过设置Write Concern来设置写成功的规则。

搭建过程

一主两从:
主机:192.168.73.133
主节点:27017
从节点:27018、27019

  • 创建rs文件夹,然后在其下创建3个用于存放节点信息及配置的节点文件夹

    1. cd /usr/local/mongo-5.0.1/bin/
    2. mkdir rs
    3. cd ./rs
    4. mkdir 27017 27018 27019
  • 以27017为例,其余两个节点文件夹也按如下操作

    1. cd ./27017
    2. # 创建用于存储数据和日志的文件夹
    3. mkdir data log
    4. # 创建mongo.conf配置文件,并编写相关配置
    5. vi mongo.conf
    1. systemLog:
    2. destination: file
    3. logAppend: true
    4. # 日志文件存储路径
    5. path: /usr/local/mongo-5.0.1/bin/rs/27017/log/mongod.log
    6. storage:
    7. # 数据存储位置
    8. dbPath: /usr/local/mongo-5.0.1/bin/rs/27017/data
    9. journal:
    10. enabled: true
    11. processManagement:
    12. # 后台运行
    13. fork: true
    14. # 要事先创建/var/run/mongo文件夹
    15. pidFilePath: /var/run/mongo/mongod_27017.pid
    16. timeZoneInfo: /usr/share/zoneinfo
    17. net:
    18. port: 27017
    19. # 允许任何ip访问
    20. bindIp: 0.0.0.0
    21. replication:
    22. # 复制集的名称,可为任意名称
    23. replSetName: rs
  • 如果不想一个一个改,可以先复制27017文件夹中的内容,然后批量替换文件中的内容,以27018为例 ```bash cd ../ cp -r ./27017/* ./27018/

sed -i “s/查找字段/替换字段/g” grep 查找字段 -rl 路径

sed -i “s/27017/27018/g” grep 27017 -rl /usr/local/mongo-5.0.1/bin/rs/27018/mongo.conf

ps:记得也要检查一下,防止不小心出错哦

  1. - 启动3个mongo服务实例节点
  2. ```bash
  3. cd ../
  4. ./mongod -f ./rs/27017/mongo.conf
  5. ./mongod -f ./rs/27018/mongo.conf
  6. ./mongod -f ./rs/27019/mongo.conf
  • 连接到任意节点,进行复制集的初始化和配置 ```bash

    第一种方式

    ./mongo 192.168.73.133:27017 rs.initiate({ _id:”rs”, members:[ {_id:0, host:”192.168.73.133:27017”}, {_id:1, host:”192.168.73.133:27018”}, {_id:2, host:”192.168.73.133:27019”}] })

第二种方式

./mongo 192.168.73.133:27017 rs.initiate() rs.add(“192.168.73.133:27018”) rs.add(“192.168.73.133:27019”)

查看副本集的配置

rs.conf()

查看副本集状态

rs.status()

查看该主机节点是否为副本集主节点

rs.isMaster()

  1. - 设置从节点可读
  2. ```bash
  3. rs:SECONDARY> db.setSecondaryOk()

分片集群

原理介绍

搭建过程

三主六从、三配置服务实例、三路由服务实例
image.png

角色 主机 端口
shard1 192.168.73.133 27017、27018、27019
shard2 192.168.73.133 27020、27021、27022
shard3 192.168.73.133 27023、27024、27025
config-servers 192.168.73.133 27026、27027、27028
route-servers 192.168.73.133 27029、27030、27031

image.png

  • 按照上图所示,在 /usr/local/mongo-5.0.1/bin/sharding/ 目录下创建相应的目录及文件
  • 分片服务节点 mongo.conf 的配置,以27017为例,分片中的节点按如下方式做相应修改即可

    1. systemLog:
    2. destination: file
    3. logAppend: true
    4. path: /usr/local/mongo-5.0.1/bin/sharding/shard1/27017/log/mongod.log
    5. storage:
    6. dbPath: /usr/local/mongo-5.0.1/bin/sharding/shard1/27017/data
    7. journal:
    8. enabled: true
    9. processManagement:
    10. fork: true
    11. pidFilePath: /var/run/mongo/mongod_27017.pid
    12. net:
    13. bindIp: 0.0.0.0
    14. port: 27017
    15. replication:
    16. # mongo服务实例的复制集名称
    17. replSetName: rs1
    18. sharding:
    19. clusterRole: shardsvr
  • 配置服务节点 mongo.conf 的配置,以27026为例,其它两个配置节点按如下方式做相应修改即可

    1. systemLog:
    2. destination: file
    3. logAppend: true
    4. path: /usr/local/mongo-5.0.1/bin/sharding/config-servers/27026/log/mongod.log
    5. storage:
    6. dbPath: /usr/local/mongo-5.0.1/bin/sharding/config-servers/27026/data
    7. journal:
    8. enabled: true
    9. processManagement:
    10. fork: true
    11. pidFilePath: /var/run/mongo/mongod_27026.pid
    12. timeZoneInfo: /usr/share/zoneinfo
    13. net:
    14. bindIp: 0.0.0.0
    15. port: 27026
    16. replication:
    17. # 配置服务实例的复制集名称
    18. replSetName: config
    19. sharding:
    20. clusterRole: configsvr
  • 路由服务节点 mongo.conf 的配置,以27029为例,其它两个路由节点按如下方式做相应修改即可

    1. systemLog:
    2. destination: file
    3. logAppend: true
    4. path: /usr/local/mongo-5.0.1/bin/sharding/mongos-servers/27029/log/mongos.log
    5. processManagement:
    6. fork: true
    7. pidFilePath: /var/run/mongo/mongos_27029.pid
    8. net:
    9. bindIp: 0.0.0.0
    10. port: 27029
    11. sharding:
    12. # 这里写的是配置服务复制集名称
    13. configDB: config/192.168.73.133:27026,192.168.73.133:27027,192.168.73.133:27028
  • 启动三个分片中的服务实例节点,并初始化复制集 ```bash cd /usr/local/mongo-5.0.1/bin/

shard1

./mongod -f ./sharding/shard1/27017/mongo.conf ./mongod -f ./sharding/shard1/27018/mongo.conf ./mongod -f ./sharding/shard1/27019/mongo.conf

./mongo 192.168.73.133:27017 rs.initiate({ _id:”rs1”, members:[ {_id:0, host:”192.168.73.133:27017”}, {_id:1, host:”192.168.73.133:27018”}, {_id:2, host:”192.168.73.133:27019”}] })

shard2

./mongod -f ./sharding/shard2/27020/mongo.conf ./mongod -f ./sharding/shard2/27021/mongo.conf ./mongod -f ./sharding/shard2/27022/mongo.conf

./mongo 192.168.73.133:27020 rs.initiate({ _id:”rs2”, members:[ {_id:0, host:”192.168.73.133:27020”}, {_id:1, host:”192.168.73.133:27021”}, {_id:2, host:”192.168.73.133:27022”}] })

shard3

./mongod -f ./sharding/shard3/27023/mongo.conf ./mongod -f ./sharding/shard3/27024/mongo.conf ./mongod -f ./sharding/shard3/27025/mongo.conf

./mongo 192.168.73.133:27023 rs.initiate({ _id:”rs3”, members:[ {_id:0, host:”192.168.73.133:27023”}, {_id:1, host:”192.168.73.133:27024”}, {_id:2, host:”192.168.73.133:27025”}] })

  1. - 启动配置中的服务实例节点,并初始化复制集
  2. ```bash
  3. ./mongod -f ./sharding/config-servers/27026/mongo.conf
  4. ./mongod -f ./sharding/config-servers/27027/mongo.conf
  5. ./mongod -f ./sharding/config-servers/27028/mongo.conf
  6. ./mongo 192.168.73.133:27026
  7. rs.initiate({ _id:"config", members:[
  8. {_id:0, host:"192.168.73.133:27026"},
  9. {_id:1, host:"192.168.73.133:27027"},
  10. {_id:2, host:"192.168.73.133:27028"}]
  11. })
  • 启动路由服务实例节点

    1. ./mongos -f ./sharding/mongos-servers/27029/mongo.conf
    2. ./mongos -f ./sharding/mongos-servers/27030/mongo.conf
    3. ./mongos -f ./sharding/mongos-servers/27031/mongo.conf
  • 连接任意路由节点,添加分片 ```bash ./mongo —host 192.168.73.133 —port 27029

命令方式

sh.addShard(“rs1/192.168.73.133:27017,192.168.73.133:27018,192.168.73.133:27019”) sh.addShard(“rs2/192.168.73.133:27020,192.168.73.133:27021,192.168.73.133:27022”) sh.addShard(“rs3/192.168.73.133:27023,192.168.73.133:27024,192.168.73.133:27025”)

api方式

db.runCommand({addshard:”rs1/192.168.73.133:27017,192.168.73.133:27018,192.168.73.133:27019”,name:”shard1”}) db.runCommand({addshard:”rs2/192.168.73.133:27020,192.168.73.133:27021,192.168.73.133:27022”,name:”shard2”}) db.runCommand({addshard:”rs3/192.168.73.133:27023,192.168.73.133:27024,192.168.73.133:27025”,name:”shard3”})

查看集群状态

sh.status()

  1. - 对数据库进行分片
  2. ```bash
  3. # 命令方式
  4. sh.enableSharding("db_student")
  5. sh.shardCollection("db_student.student",{"id":"hashed"})
  6. # api方式
  7. db.runCommand({enablesharding:"db_student")
  8. db.runCommand({shardcollection:"db_student.student",key:{id:1}})
  9. # 写入数据
  10. use db_student
  11. for(i=1;i<=5000;i++){db.student.insert({"id":i,"name":"ble"+i})}

.NET集成

.NET6WebAPIMongo

前提

  • 引入Nuget包
    • MongoDB.Driver
  • 在appsettings.json文件中,配置Mongo的相关参数

    1. {
    2. "Logging": {
    3. "LogLevel": {
    4. "Default": "Information",
    5. "Microsoft.AspNetCore": "Warning"
    6. }
    7. },
    8. "AllowedHosts": "*",
    9. "Mongo": {
    10. "Host": "localhost",
    11. "Port": 27017,
    12. "Database": "your database name"
    13. }
    14. }
  • 接下来,我们简单定义一个MongoOptions配置类,用于接收配置

    1. public class MongoOptions
    2. {
    3. public string Host { get; set; } = null!;
    4. public int Port { get; set; }
    5. public string? Database { get; set; }
    6. public string ConnectionString => $"mongodb://{Host}:{Port}/{Database}";
    7. }
  • 自定义ServiceCollectionExtensions扩展类

    • 自定义AddMongo扩展方法,在这里对Mongo进行引入

      1. public static partial class ServiceCollectionExtensions
      2. {
      3. public static void AddMongo(this IServiceCollection? services, Action<MongoOptions> configure)
      4. {
      5. MongoOptions mongoOptions = new();
      6. configure?.Invoke(mongoOptions);
      7. IMongoClient mongoClient = new MongoClient(mongoOptions.ConnectionString);
      8. services!.AddScoped(serviceProvider => mongoClient);
      9. IMongoDatabase mongoDatabase = mongoClient.GetDatabase(mongoOptions.Database);
      10. services!.AddScoped(serviceProvider => mongoDatabase);
      11. }
      12. }
    • 在Program类中,使用我们刚才定义的扩展方法 ```csharp var builder = WebApplication.CreateBuilder(args); var services = builder.Services; var configuration = builder.Configuration;

services.AddControllers(); services.AddEndpointsApiExplorer(); services.AddSwaggerGen();

// here services.AddMongo(opt => { opt.Host = configuration[“Mongo:Host”]; opt.Port = int.TryParse(configuration[“Mongo:Port”], out int port) ? port : default; opt.Database = configuration[“Mongo:Database”]; });

var app = builder.Build();

if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); }

app.UseAuthorization();

app.MapControllers();

app.Run();

  1. - 因为每个集合中都会有一个`ObjectId`类型的主键,所以我们给每个集合定义一个基类
  2. ```csharp
  3. public class MongoCollection
  4. {
  5. [BsonId]
  6. public ObjectId Id { get; set; }
  7. }
  • 接下来,是我简单为IMongoDatabase和IMongoCollection扩展的一些功能,你可以直接拿去用呢😀

    1. public static class MongoExtensions
    2. {
    3. /// <summary>
    4. /// 集合是否存在
    5. /// </summary>
    6. public static async Task<bool> CollectionExistsAsync<TCollection>(this IMongoDatabase mongoDatabase, CancellationToken cancellationToken = default)
    7. where TCollection : MongoCollection
    8. {
    9. string collectionName = typeof(TCollection).Name;
    10. BsonDocument filter = new("name", BsonValue.Create(collectionName));
    11. ListCollectionsOptions options = new()
    12. {
    13. Filter = filter
    14. };
    15. using IAsyncCursor<BsonDocument> cursor = await mongoDatabase.ListCollectionsAsync(options, cancellationToken);
    16. bool collectionIsExists = await cursor.AnyAsync(cancellationToken);
    17. return collectionIsExists;
    18. }
    19. /// <summary>
    20. /// 获取所有集合名称
    21. /// </summary>
    22. public static async Task<List<string>> GetCollectionNamesAsync(this IMongoDatabase mongoDatabase, ListCollectionNamesOptions? options = null, CancellationToken cancellationToken = default)
    23. {
    24. using IAsyncCursor<string> cursor = await mongoDatabase.ListCollectionNamesAsync(options, cancellationToken);
    25. List<string> collectionNames = await cursor.ToListAsync(cancellationToken);
    26. return collectionNames;
    27. }
    28. /// <summary>
    29. /// 创建集合
    30. /// </summary>
    31. public static async Task CreateCollectionAsync<TCollection>(this IMongoDatabase mongoDatabase, CreateCollectionOptions? collectionOptions = null, CancellationToken cancellationToken = default)
    32. where TCollection : MongoCollection
    33. {
    34. string collectionName = typeof(TCollection).Name;
    35. await mongoDatabase.CreateCollectionAsync(collectionName, collectionOptions, cancellationToken);
    36. }
    37. /// <summary>
    38. /// 获取集合对象
    39. /// </summary>
    40. public static IMongoCollection<TDocument> GetCollection<TDocument>(this IMongoDatabase mongoDatabase, MongoCollectionSettings? settings = null)
    41. where TDocument : MongoCollection
    42. {
    43. string collectionName = typeof(TDocument).Name;
    44. IMongoCollection<TDocument> mongoCollection = mongoDatabase.GetCollection<TDocument>(collectionName, settings);
    45. return mongoCollection;
    46. }
    47. /// <summary>
    48. /// 获取集合对象
    49. /// </summary>
    50. public static IMongoCollection<BsonDocument> GetCollection(this IMongoDatabase mongoDatabase, string collectionName, MongoCollectionSettings? settings = null)
    51. {
    52. IMongoCollection<BsonDocument> mongoCollection = mongoDatabase.GetCollection<BsonDocument>(collectionName, settings);
    53. return mongoCollection;
    54. }
    55. /// <summary>
    56. /// 插入一条文档
    57. /// </summary>
    58. public static async Task<TDocument> InsertAsync<TDocument>(this IMongoCollection<TDocument> mongoCollection, TDocument document, InsertOneOptions? options = null, CancellationToken cancellationToken = default)
    59. where TDocument : MongoCollection
    60. {
    61. await mongoCollection.InsertOneAsync(document, options, cancellationToken);
    62. return document;
    63. }
    64. /// <summary>
    65. /// 插入多条文档
    66. /// </summary>
    67. public static async Task<List<TDocument>> InsertAsync<TDocument>(this IMongoCollection<TDocument> mongoCollection, List<TDocument> documents, InsertManyOptions? options = null, CancellationToken cancellationToken = default)
    68. where TDocument : MongoCollection
    69. {
    70. await mongoCollection.InsertManyAsync(documents, options, cancellationToken);
    71. List<TDocument> documentsInserted = documents.ToList();
    72. return documentsInserted;
    73. }
    74. /// <summary>
    75. /// 根据 _id 查询文档,并将查询结果投影为 TProjection 类型
    76. /// </summary>
    77. public static async Task<TProjection> FindByIdAsync<TDocument, TProjection>(this IMongoCollection<TDocument> mongoCollection, string _id, CancellationToken cancellationToken = default)
    78. where TDocument : MongoCollection
    79. where TProjection : class
    80. {
    81. FilterDefinition<TDocument> filter = Builders<TDocument>.Filter.Eq("_id", new ObjectId(_id));
    82. FindOptions<TDocument, TProjection> options = new()
    83. {
    84. Projection = Builders<TDocument>.Projection.As<TProjection>()
    85. };
    86. using IAsyncCursor<TProjection> cursor = await mongoCollection.FindAsync(filter, options, cancellationToken);
    87. TProjection projection = await cursor.FirstOrDefaultAsync(cancellationToken);
    88. return projection;
    89. }
    90. /// <summary>
    91. /// 根据 _id 查询文档
    92. /// </summary>
    93. public static async Task<TDocument> FindByIdAsync<TDocument>(this IMongoCollection<TDocument> mongoCollection, string _id, CancellationToken cancellationToken = default)
    94. where TDocument : MongoCollection
    95. {
    96. FilterDefinition<TDocument> filter = Builders<TDocument>.Filter.Eq("_id", new ObjectId(_id));
    97. using IAsyncCursor<TDocument> cursor = await mongoCollection.FindAsync(filter, cancellationToken: cancellationToken);
    98. TDocument document = await cursor.FirstOrDefaultAsync(cancellationToken);
    99. return document;
    100. }
    101. /// <summary>
    102. /// 查询符合条件的第一条文档,并将查询结果投影为 TProjection 类型
    103. /// </summary>
    104. public static async Task<TProjection> FindOneAsync<TDocument, TProjection>(this IMongoCollection<TDocument> mongoCollection, FilterDefinition<TDocument> filter, SortDefinition<TDocument>? sort = null, CancellationToken cancellationToken = default)
    105. where TDocument : MongoCollection
    106. where TProjection : class
    107. {
    108. FindOptions<TDocument, TProjection> options = new()
    109. {
    110. Sort = sort,
    111. Projection = Builders<TDocument>.Projection.As<TProjection>()
    112. };
    113. using IAsyncCursor<TProjection> cursor = await mongoCollection.FindAsync(filter, options, cancellationToken);
    114. TProjection projection = await cursor.FirstOrDefaultAsync(cancellationToken);
    115. return projection;
    116. }
    117. /// <summary>
    118. /// 查询符合条件的第一条文档
    119. /// </summary>
    120. public static async Task<TDocument> FindOneAsync<TDocument>(this IMongoCollection<TDocument> mongoCollection, FilterDefinition<TDocument> filter, SortDefinition<TDocument>? sort = null, CancellationToken cancellationToken = default)
    121. where TDocument : MongoCollection
    122. {
    123. FindOptions<TDocument> options = new()
    124. {
    125. Sort = sort
    126. };
    127. using IAsyncCursor<TDocument> cursor = await mongoCollection.FindAsync(filter, options, cancellationToken);
    128. TDocument document = await cursor.FirstOrDefaultAsync(cancellationToken);
    129. return document;
    130. }
    131. /// <summary>
    132. /// 查询符合条件的多条文档,并将查询结果投影为 TProjection 类型
    133. /// </summary>
    134. public static async Task<List<TProjection>> FindManyAsync<TDocument, TProjection>(this IMongoCollection<TDocument> mongoCollection, FilterDefinition<TDocument> filter, SortDefinition<TDocument>? sort = null, int? pageIndex = null, int? pageSize = null, CancellationToken cancellationToken = default)
    135. where TDocument : MongoCollection
    136. where TProjection : class
    137. {
    138. FindOptions<TDocument, TProjection> options = new()
    139. {
    140. Sort = sort,
    141. Projection = Builders<TDocument>.Projection.As<TProjection>(),
    142. Skip = pageSize * (pageIndex - 1),
    143. Limit = pageSize
    144. };
    145. using IAsyncCursor<TProjection> cursor = await mongoCollection.FindAsync(filter, options, cancellationToken);
    146. List<TProjection> projections = await cursor.ToListAsync(cancellationToken);
    147. return projections;
    148. }
    149. /// <summary>
    150. /// 查询符合条件的多条文档
    151. /// </summary>
    152. public static async Task<List<TDocument>> FindManyAsync<TDocument>(this IMongoCollection<TDocument> mongoCollection, FilterDefinition<TDocument> filter, SortDefinition<TDocument>? sort = null, int? pageIndex = null, int? pageSize = null, CancellationToken cancellationToken = default)
    153. where TDocument : MongoCollection
    154. {
    155. FindOptions<TDocument> options = new()
    156. {
    157. Sort = sort,
    158. Skip = pageSize * (pageIndex - 1),
    159. Limit = pageSize
    160. };
    161. using IAsyncCursor<TDocument> cursor = await mongoCollection.FindAsync(filter, options, cancellationToken);
    162. List<TDocument> documents = await cursor.ToListAsync(cancellationToken);
    163. return documents;
    164. }
    165. /// <summary>
    166. /// 查询所有文档,并将查询结果投影为 TProjection 类型
    167. /// </summary>
    168. public static async Task<List<TProjection>> FindAllAsync<TDocument, TProjection>(this IMongoCollection<TDocument> mongoCollection, SortDefinition<TDocument>? sort = null, int? pageIndex = null, int? pageSize = null, CancellationToken cancellationToken = default)
    169. where TDocument : MongoCollection
    170. where TProjection : class
    171. {
    172. FilterDefinition<TDocument> emptyFilter = Builders<TDocument>.Filter.Empty;
    173. FindOptions<TDocument, TProjection> options = new()
    174. {
    175. Sort = sort,
    176. Projection = Builders<TDocument>.Projection.As<TProjection>(),
    177. Skip = pageSize * (pageIndex - 1),
    178. Limit = pageSize
    179. };
    180. using IAsyncCursor<TProjection> cursor = await mongoCollection.FindAsync(emptyFilter, options, cancellationToken);
    181. List<TProjection> projections = await cursor.ToListAsync(cancellationToken);
    182. return projections;
    183. }
    184. /// <summary>
    185. /// 查询所有文档
    186. /// </summary>
    187. public static async Task<List<TDocument>> FindAllAsync<TDocument>(this IMongoCollection<TDocument> mongoCollection, SortDefinition<TDocument>? sort = null, int? pageIndex = null, int? pageSize = null, CancellationToken cancellationToken = default)
    188. where TDocument : MongoCollection
    189. {
    190. FilterDefinition<TDocument> emptyFilter = Builders<TDocument>.Filter.Empty;
    191. FindOptions<TDocument> options = new()
    192. {
    193. Sort = sort,
    194. Skip = pageSize * (pageIndex - 1),
    195. Limit = pageSize
    196. };
    197. using IAsyncCursor<TDocument> cursor = await mongoCollection.FindAsync(emptyFilter, options, cancellationToken);
    198. List<TDocument> documents = await cursor.ToListAsync(cancellationToken);
    199. return documents;
    200. }
    201. /// <summary>
    202. /// 更新查询到的第一个文档
    203. /// </summary>
    204. public static async Task<UpdateResult> UpdateFirstAsync<TDocument>(this IMongoCollection<TDocument> mongoCollection, FilterDefinition<TDocument> filter, UpdateDefinition<TDocument> update, CancellationToken cancellationToken = default)
    205. where TDocument : MongoCollection
    206. {
    207. UpdateResult updateResult = await mongoCollection.UpdateOneAsync(filter, update, null, cancellationToken);
    208. return updateResult;
    209. }
    210. /// <summary>
    211. /// 更新查询到的第一个文档,如果没有找到就创建并插入一个新文档
    212. /// </summary>
    213. public static async Task<UpdateResult> UpsertAsync<TDocument>(this IMongoCollection<TDocument> mongoCollection, FilterDefinition<TDocument> filter, UpdateDefinition<TDocument> update, CancellationToken cancellationToken = default)
    214. where TDocument : MongoCollection
    215. {
    216. UpdateOptions options = new()
    217. {
    218. IsUpsert = true
    219. };
    220. UpdateResult updateResult = await mongoCollection.UpdateOneAsync(filter, update, options, cancellationToken);
    221. return updateResult;
    222. }
    223. }
  • 再来两个模型类用来测试吧~ ```csharp public class Student : MongoCollection { public string Name { get; set; } = null!;

    public StudentClass? StudentClass { get; set; } }

public class StudentClass : MongoCollection { public int ClassId { get; set; }

  1. public string ClassName { get; set; } = null!;

}

  1. - 至此,准备工作就完成了。我们可以在需要使用的地方注入`IMongoClient`或`IMongoDatabase`即可🤗
  2. <a name="Krst6"></a>
  3. ## 集合操作
  4. - 创建一个没有大小限制的集合,也是默认集合创建方式
  5. ```csharp
  6. if (!await MongoDatabase.CollectionExistsAsync<Student>())
  7. {
  8. await MongoDatabase.CreateCollectionAsync<Student>();
  9. }
  10. List<string> collectionNames = await MongoDatabase.GetCollectionNamesAsync();
  • 创建固定集合。固定集合是指有着固定大小的集合,当达到最大值时,它会自动覆盖最早的文档

    1. if (!await MongoDatabase.CollectionExistsAsync<Student>())
    2. {
    3. CreateCollectionOptions collectionOptions = new()
    4. {
    5. // 固定集合
    6. Capped = true,
    7. // 固定集合指定一个最大值(单位: kb)
    8. MaxSize = 1024,
    9. // 指定固定集合中包含文档的最大数量
    10. MaxDocuments = 100
    11. };
    12. await MongoDatabase.CreateCollectionAsync<Student>(collectionOptions);
    13. }
  • 创建带数据校验的集合,在文件进行插入与更新时进行数据校验

    1. if (!await MongoDatabase.CollectionExistsAsync<Student>())
    2. {
    3. FilterDefinition<Student> validator = Builders<Student>.Filter.Where(student => student.Name.Length == 3);
    4. CreateCollectionOptions<Student> collectionOptions = new()
    5. {
    6. Validator = validator,
    7. // 设置效验级别
    8. ValidationLevel = DocumentValidationLevel.Strict,
    9. // 设置效验不通过后执行的动作
    10. ValidationAction = DocumentValidationAction.Error
    11. };
    12. await MongoDatabase.CreateCollectionAsync<Student>(collectionOptions);
    13. }

文档操作

插入

  • 若新增数据的主键已经存在,则会抛异常提示主键重复,不保存当前数据

    1. StudentClass studentClass = new()
    2. {
    3. ClassId = 2,
    4. ClassName = "向日葵班"
    5. };
    6. Student student = new()
    7. {
    8. Name = "ble",
    9. StudentClass = studentClass
    10. };
    11. IMongoCollection<Student> collection = MongoDatabase.GetCollection<Student>();
    12. student = await collection.InsertAsync(student);
  • 批量新增 ```csharp List students = new(); StudentClass studentClass = new() { ClassId = 1, ClassName = “玫瑰班” }; for (int i = 0; i < 10; i++) { Student student = new() {

    1. Name = $"name{i + 1}",
    2. StudentClass = studentClass

    }; students.Add(student); }

IMongoCollection collection = MongoDatabase.GetCollection(); students = await collection.InsertAsync(students);

  1. <a name="WvudM"></a>
  2. ### 查询
  3. - 查询全部
  4. ```csharp
  5. IMongoCollection<Student> collection = MongoDatabase.GetCollection<Student>();
  6. List<Student> students = await collection.FindAllAsync();
  • 根据文档Id查询

    1. string id = "6236adfd92548cce8ac61482";
    2. IMongoCollection<Student> collection = MongoDatabase.GetCollection<Student>();
    3. Student? student = await collection.FindByIdAsync(id);
  • 查询集合中,存在指定字段的文档数据

    1. // 查询所有存在"ClassId"字段且值为1的文档
    2. int classId = 2;
    3. FilterDefinition<Student> filter1 = Builders<Student>.Filter.Exists(student => student.StudentClass!.ClassId, true);
    4. FilterDefinition<Student> filter2 = Builders<Student>.Filter.Eq(student => student.StudentClass!.ClassId, classId);
    5. FilterDefinition<Student> filter = Builders<Student>.Filter.And(filter1, filter2);
    6. IMongoCollection<Student> collection = MongoDatabase.GetCollection<Student>();
    7. List<Student> students = await collection.FindManyAsync(filter);
  • 模糊查询

    1. string name = "bl";
    2. FilterDefinition<Student> filter1 = Builders<Student>.Filter.Gte(student => student.StudentClass!.ClassId, 2);
    3. FilterDefinition<Student> filter2 = Builders<Student>.Filter.Lte(student => student.StudentClass!.ClassId, 2);
    4. FilterDefinition<Student> filter3 = Builders<Student>.Filter.Regex(student => student.Name, $"^.*{name}.*$");
    5. FilterDefinition<Student> filter = Builders<Student>.Filter.And(filter1, filter2, filter3);
    6. IMongoCollection<Student> collection = MongoDatabase.GetCollection<Student>();
    7. List<Student> students = await collection.FindManyAsync(filter);
  • 排序

    1. FilterDefinition<Student> emptyFilter = Builders<Student>.Filter.Empty;
    2. SortDefinition<Student> sort = Builders<Student>.Sort.Descending(student => student.StudentClass!.ClassId).Ascending(student => student.Name);
    3. IMongoCollection<Student> collection = MongoDatabase.GetCollection<Student>();
    4. List<Student> students = await collection.FindManyAsync(emptyFilter, sort);
  • IN查询

    1. List<int> classIds = new() { 2, 3 };
    2. // In查询
    3. FilterDefinition<Student> filter = Builders<Student>.Filter.In(student => student.StudentClass!.ClassId, classIds);
    4. IMongoCollection<Student> collection = MongoDatabase.GetCollection<Student>();
    5. List<Student> students = await collection.FindManyAsync(filter);
  • 查询符合条件的文档数量

    1. FilterDefinition<Student> filter = Builders<Student>.Filter.Empty;
    2. IMongoCollection<Student> collection = MongoDatabase.GetCollection<Student>();
    3. long count = await collection.CountDocumentsAsync(filter);

    更新

  • 更新查询到的第一个文档,如果没有找到就创建并插入一个新文档

    1. IMongoCollection<Student> collection = MongoDatabase.GetCollection<Student>();
    2. FilterDefinition<Student> filter = Builders<Student>.Filter.Regex(student => student.Name, "name that does not exist.");
    3. UpdateDefinition<Student> updateDefinition = Builders<Student>.Update
    4. .Set(student => student.Name, "nini")
    5. .Set(student => student.StudentClass!.ClassId, 2);
    6. UpdateResult updateResult = await collection.UpsertAsync(filter, updateDefinition);
  • 更新查询到的第一个文档

    1. IMongoCollection<Student> collection = MongoDatabase.GetCollection<Student>();
    2. FilterDefinition<Student> filter = Builders<Student>.Filter.Regex(student => student.Name, "^.*name.*$");
    3. UpdateDefinition<Student> updateDefinition = Builders<Student>.Update
    4. .Set(student => student.Name, "fengjian")
    5. .Set(student => student.StudentClass!.ClassId, 2);
    6. UpdateResult updateResult = await collection.UpdateFirstAsync(filter, updateDefinition);
  • 更新查询到的所有文档

    1. IMongoCollection<Student> collection = MongoDatabase.GetCollection<Student>();
    2. FilterDefinition<Student> filter = Builders<Student>.Filter.Eq(student => student.StudentClass!.ClassId, 1);
    3. UpdateDefinition<Student> updateDefinition = Builders<Student>.Update
    4. .Set(student => student.Name, "rose");
    5. UpdateResult updateResult = await collection.UpdateManyAsync(filter, updateDefinition);

删除

  • 删除符合条件的第一个文档

    1. IMongoCollection<Student> collection = MongoDatabase.GetCollection<Student>();
    2. FilterDefinition<Student> filter = Builders<Student>.Filter.Eq(student => student.Name, "rose7");
    3. DeleteResult deleteResult = await collection.DeleteOneAsync(filter);
  • 删除符合条件的全部文档,并返回删除的文档

    1. IMongoCollection<Student> collection = MongoDatabase.GetCollection<Student>();
    2. FilterDefinition<Student> filter = Builders<Student>.Filter.Eq(student => student.Name, "rose6");
    3. DeleteResult deleteResult = await collection.DeleteManyAsync(filter);

管道操作

$group

  1. db.createCollection("student")
  2. db.student.insert([{
  3. "name": "mike",
  4. "sex": "男",
  5. "age": 20
  6. },   {
  7. "name": "Marry",
  8. "sex": "女",
  9. "age": 25
  10. },   {
  11. "name": "Tom",
  12. "sex": "女",
  13. "age": 35
  14. },   {
  15. "name": "Joe",
  16. "sex": "女",
  17. "age": 35
  18. },   {
  19. "name": "Joe",
  20. "sex": "女",
  21. "age": 45
  22. },   {
  23. "name": "John",
  24. "sex": "男",
  25. "age": 45
  26. }])
  1. IMongoCollection<BsonDocument> collection = MongoDatabase.GetCollection(collectionName: "student");
  2. // 数据匹配过滤
  3. BsonDocument match = new()
  4. {
  5. { "age", new BsonDocument("$eq", 45) }
  6. };
  7. // 聚合函数相关
  8. BsonDocument group = new()
  9. {
  10. // 分组key
  11. { "_id", "$sex" },
  12. // 每组男女数量
  13. { "count", new BsonDocument("$sum", 1) },
  14. { "totalAge", new BsonDocument("$sum", "$age") },
  15. { "avgAge", new BsonDocument("$avg", "$age") },
  16. { "maxAge", new BsonDocument("$max", "$age") },
  17. { "minAge", new BsonDocument("$min", "$age") }
  18. };
  19. IAggregateFluent<BsonDocument> aggregate = collection.Aggregate()
  20. .Match(match)
  21. .Group(group);
  22. List<BsonDocument> bsons = await aggregate.ToListAsync();

$sort

  1. IMongoCollection<BsonDocument> collection = MongoDatabase.GetCollection(collectionName: "student");
  2. BsonDocument group = new()
  3. {
  4. { "_id", "$age" },
  5. { "count", new BsonDocument("$sum", 1) }
  6. };
  7. BsonDocument sort = new()
  8. {
  9. { "count", -1 }
  10. };
  11. // 分组后根据某字段排序
  12. IAggregateFluent<BsonDocument> aggregate = collection.Aggregate()
  13. .Group(group)
  14. .SortBy(bson => bson["_id"])
  15. .ThenByDescending(bson => bson["count"]);
  16. List<BsonDocument> bsons = await aggregate.ToListAsync();

$skip - $limit

  1. IMongoCollection<BsonDocument> collection = MongoDatabase.GetCollection(collectionName: "student");
  2. BsonDocument group = new()
  3. {
  4. { "_id", "$age" },
  5. { "count", new BsonDocument("$sum", 1) }
  6. };
  7. // 将分组结果进行分页操作
  8. IAggregateFluent<BsonDocument> aggregate = collection.Aggregate()
  9. .Group(group)
  10. .Skip(1)
  11. .Limit(1);
  12. List<BsonDocument> bsons = await aggregate.ToListAsync();

$project

  1. IMongoCollection<BsonDocument> collection = MongoDatabase.GetCollection(collectionName: "student");
  2. BsonDocument group = new()
  3. {
  4. { "_id", "$sex" },
  5. { "count", new BsonDocument("$sum", 1) },
  6. { "totalAge", new BsonDocument("$sum", "$age") },
  7. { "avgAge", new BsonDocument("$avg", "$age") },
  8. { "maxAge", new BsonDocument("$max", "$age") },
  9. { "minAge", new BsonDocument("$min", "$age") }
  10. };
  11. // 投影,控制需要显示的字段
  12. IAggregateFluent<BsonDocument> aggregate = collection.Aggregate()
  13. .Group(group)
  14. .Project<BsonDocument>(Builders<BsonDocument>.Projection
  15. .Include("maxAge")
  16. .Include("minAge")
  17. );
  18. List<BsonDocument> bsons = await aggregate.ToListAsync();

$match

  1. IMongoCollection<BsonDocument> collection = MongoDatabase.GetCollection(collectionName: "student");
  2. BsonDocument group = new()
  3. {
  4. { "_id", "$sex" },
  5. { "count", new BsonDocument("$sum", 1) },
  6. { "avgAge", new BsonDocument("$avg", "$age") }
  7. };
  8. BsonDocument match = new()
  9. {
  10. { "avgAge", new BsonDocument("$gte", 20) }
  11. };
  12. // 分组后,平均年龄大于等于20的第一条数据
  13. BsonDocument bson = await collection.Aggregate()
  14. .Group(group)
  15. .Match(match)
  16. .FirstOrDefaultAsync();

$push

  1. db.createCollection("sales")
  2. db.sales.insert([{
  3. "item": "abc",
  4. "price": 10,
  5. "quantity": 2,
  6. "date": ISODate("2014-01-01T08:00:00Z")
  7. }, {
  8. "item": "jkl",
  9. "price": 20,
  10. "quantity": 1,
  11. "date": ISODate("2014-02-03T09:00:00Z")
  12. }, {
  13. "item": "xyz",
  14. "price": 5,
  15. "quantity": 5,
  16. "date": ISODate("2014-02-03T09:05:00Z")
  17. }, {
  18. "item": "abc",
  19. "price": 10,
  20. "quantity": 10,
  21. "date": ISODate("2014-02-15T08:00:00Z")
  22. }, {
  23. "item": "xyz",
  24. "price": 5,
  25. "quantity": 10,
  26. "date": ISODate("2014-02-15T09:05:00Z")
  27. }, {
  28. "item": "xyz",
  29. "price": 5,
  30. "quantity": 5,
  31. "date": ISODate("2014-02-15T12:05:10Z")
  32. }, {
  33. "item": "xyz",
  34. "price": 5,
  35. "quantity": 10,
  36. "date": ISODate("2014-02-15T14:12:12Z")
  37. }])
  1. IMongoCollection<BsonDocument> collection = MongoDatabase.GetCollection(collectionName: "sales");
  2. BsonDocument group = new()
  3. {
  4. {
  5. "_id",
  6. new BsonDocument
  7. {
  8. { "day", new BsonDocument("$dayOfYear", "$date") },
  9. { "year", new BsonDocument("$year", "$date") }
  10. }
  11. },
  12. {
  13. "itemsSold",
  14. new BsonDocument
  15. {
  16. {
  17. "$push", new BsonDocument
  18. {
  19. { "item", "$item" },
  20. { "quantity", "$quantity" }
  21. }
  22. }
  23. }
  24. }
  25. };
  26. IAggregateFluent<BsonDocument> aggregate = collection.Aggregate().Group(group);
  27. List<BsonDocument> bsons = await aggregate.ToListAsync();

$unwind

  1. db.createCollection("inventory")
  2. db.inventory.insert([{
  3. "item": "ABC",
  4. price: NumberDecimal("80"),
  5. "sizes": ["B", "L", "E"]
  6. }, {
  7. "item": "EFG",
  8. price: NumberDecimal("120"),
  9. "sizes": []
  10. }, {
  11. "item": "IJK",
  12. price: NumberDecimal("160"),
  13. "sizes": "L"
  14. }, {
  15. "item": "LMN",
  16. price: NumberDecimal("10")
  17. }, {
  18. "item": "XYZ",
  19. price: NumberDecimal("5.75"),
  20. "sizes": null
  21. }])
  1. IMongoCollection<BsonDocument> collection = MongoDatabase.GetCollection(collectionName: "inventory");
  2. IAggregateFluent<BsonDocument> aggregate = collection.Aggregate()
  3. .Unwind("sizes", new AggregateUnwindOptions<BsonDocument>
  4. {
  5. IncludeArrayIndex = "index",
  6. PreserveNullAndEmptyArrays = false
  7. });
  8. List<BsonDocument> bsons = await aggregate.ToListAsync();

$bucket

  1. db.createCollection("artists")
  2. db.artists.insert([{
  3. "last_name": "Bernard",
  4. "first_name": "Emil",
  5. "year_born": 1868,
  6. "year_died": 1941,
  7. "nationality": "France"
  8. }, {
  9. "last_name": "Rippl-Ronai",
  10. "first_name": "Joszef",
  11. "year_born": 1861,
  12. "year_died": 1927,
  13. "nationality": "Hungary"
  14. }, {
  15. "last_name": "Ostroumova",
  16. "first_name": "Anna",
  17. "year_born": 1871,
  18. "year_died": 1955,
  19. "nationality": "Russia"
  20. }, {
  21. "last_name": "Van Gogh",
  22. "first_name": "Vincent",
  23. "year_born": 1853,
  24. "year_died": 1890,
  25. "nationality": "Holland"
  26. }, {
  27. "last_name": "Maurer",
  28. "first_name": "Alfred",
  29. "year_born": 1868,
  30. "year_died": 1932,
  31. "nationality": "USA"
  32. }, {
  33. "last_name": "Munch",
  34. "first_name": "Edvard",
  35. "year_born": 1863,
  36. "year_died": 1944,
  37. "nationality": "Norway"
  38. }, {
  39. "last_name": "Redon",
  40. "first_name": "Odilon",
  41. "year_born": 1840,
  42. "year_died": 1916,
  43. "nationality": "France"
  44. }, {
  45. "last_name": "Diriks",
  46. "first_name": "Edvard",
  47. "year_born": 1855,
  48. "year_died": 1930,
  49. "nationality": "Norway"
  50. }])
  1. IMongoCollection<BsonDocument> collection = MongoDatabase.GetCollection(collectionName: "artists");
  2. List<BsonDocument> stages = new()
  3. {
  4. new BsonDocument("$bucket", new BsonDocument
  5. {
  6. { "groupBy", "$year_born" },
  7. { "boundaries", BsonArray.Create(new int[]{ 1840, 1850, 1860, 1870, 1880 }) },
  8. { "default", "Other" },
  9. { "output", new BsonDocument
  10. {
  11. { "count", new BsonDocument("$sum", 1) },
  12. {
  13. "artists", new BsonDocument("$push", new BsonDocument
  14. {
  15. { "name", new BsonDocument("$concat", "['$first_name', '$last_name']") },
  16. { "year_born", "$year_born" }
  17. })
  18. }
  19. }
  20. }
  21. }),
  22. new BsonDocument("$sort", new BsonDocument("count", -1))
  23. };
  24. PipelineDefinition<BsonDocument, BsonDocument> pipeline = PipelineDefinition<BsonDocument, BsonDocument>.Create(stages);
  25. using IAsyncCursor<BsonDocument> cursor = collection.Aggregate(pipeline);
  26. List<BsonDocument> bsons = await cursor.ToListAsync();

$lookup

  1. db.createCollection("orders")
  2. db.orders.insert([{
  3. "item": "almonds",
  4. "price": 12,
  5. "quantity": 2
  6. }, {
  7. "item": "pecans",
  8. "price": 20,
  9. "quantity": 1
  10. }, {}])
  11. db.createCollection("inventory")
  12. db.inventory.insert([{
  13. "sku": "almonds",
  14. "description": "product 1",
  15. "instock": 120
  16. }, {
  17. "sku": "bread",
  18. "description": "product 2",
  19. "instock": 80
  20. }, {
  21. "sku": "cashews",
  22. "description": "product 3",
  23. "instock": 60
  24. }, {
  25. "sku": "pecans",
  26. "description": "product 4",
  27. "instock": 70
  28. }, {
  29. "sku": null,
  30. "description": "Incomplete"
  31. }, {}])
  1. IMongoCollection<BsonDocument> collection = MongoDatabase.GetCollection(collectionName: "orders");
  2. IAggregateFluent<BsonDocument> aggregate = collection.Aggregate()
  3. .Lookup(
  4. foreignCollectionName: "inventory",
  5. localField: "item",
  6. foreignField: "sku",
  7. @as: "inventory_docs"
  8. );
  9. List<BsonDocument> bsons = await aggregate.ToListAsync();
  1. List<BsonDocument> stages = new()
  2. {
  3. new BsonDocument("$lookup", new BsonDocument
  4. {
  5. { "from", "inventory" },
  6. { "localField", "item" },
  7. { "foreignField", "sku" },
  8. { "as", "inventory_docs" }
  9. })
  10. };
  11. PipelineDefinition<BsonDocument, BsonDocument> pipeline = PipelineDefinition<BsonDocument, BsonDocument>.Create(stages);
  12. using IAsyncCursor<BsonDocument> cursor = collection.Aggregate(pipeline);
  13. List<BsonDocument> bsons = await cursor.ToListAsync();

$facet

  1. db.createCollection("artwork")
  2. db.artwork.insert([{
  3. "title": "The Pillars of Society",
  4. "artist": "Grosz",
  5. "year": 1926,
  6. "price": NumberDecimal("199.99"),
  7. "tags": ["painting", "satire", "Expressionism", "caricature"]
  8. }, {
  9. "title": "Melancholy III",
  10. "artist": "Munch",
  11. "year": 1902,
  12. "price": NumberDecimal("280.00"),
  13. "tags": ["woodcut", "Expressionism"]
  14. }, {
  15. "title": "Dancer",
  16. "artist": "Miro",
  17. "year": 1925,
  18. "price": NumberDecimal("76.04"),
  19. "tags": ["oil", "Surrealism", "painting"]
  20. }, {
  21. "title": "The Great Wave off Kanagawa",
  22. "artist": "Hokusai",
  23. "price": NumberDecimal("167.30"),
  24. "tags": ["woodblock", "ukiyo-e"]
  25. }, {
  26. "title": "The Persistence of Memory",
  27. "artist": "Dali",
  28. "year": 1931,
  29. "price": NumberDecimal("483.00"),
  30. "tags": ["Surrealism", "painting", "oil"]
  31. }, {
  32. "title": "Composition VII",
  33. "artist": "Kandinsky",
  34. "year": 1913,
  35. "price": NumberDecimal("385.00"),
  36. "tags": ["oil", "painting", "abstract"]
  37. }, {
  38. "title": "The Scream",
  39. "artist": "Munch",
  40. "year": 1893,
  41. "tags": ["Expressionism", "painting", "oil"]
  42. }, {
  43. "title": "Blue Flower",
  44. "artist": "O'Keefe",
  45. "year": 1918,
  46. "price": NumberDecimal("118.42"),
  47. "tags": ["abstract", "painting"]
  48. }])
IMongoCollection<BsonDocument> collection = MongoDatabase.GetCollection(collectionName: "artwork");

List<BsonDocument> stages1 = new()
{
    new BsonDocument("$unwind", "$tags"),
    new BsonDocument("$sortByCount", "$tags")
};
PipelineDefinition<BsonDocument, BsonDocument> pipeline1 = PipelineDefinition<BsonDocument, BsonDocument>.Create(stages1);
AggregateFacet<BsonDocument, BsonDocument> aggregateFacet1 = AggregateFacet.Create("categorizedByTags", pipeline1);

List<BsonDocument> stages2 = new()
{
    new BsonDocument("$match", new BsonDocument
    {
        { "price", new BsonDocument("$exists", 1) }
    }),
    new BsonDocument("$bucket", new BsonDocument
    {
        { "groupBy", "$price" },
        { "boundaries", BsonArray.Create(new int[]{ 0, 150, 200, 300, 400 }) },
        { "default", "Other" },
        { "output", new BsonDocument
            {
                { "count", new BsonDocument("$sum", 1) },
                { "titles", new BsonDocument("$push", "$title") }
            }
        }
    })
};
PipelineDefinition<BsonDocument, BsonDocument> pipeline2 = PipelineDefinition<BsonDocument, BsonDocument>.Create(stages2);
AggregateFacet<BsonDocument, BsonDocument> aggregateFacet2 = AggregateFacet.Create("categorizedByPrice", pipeline2);

List<BsonDocument> stages3 = new()
{
    new BsonDocument("$bucketAuto", new BsonDocument
    {
        { "groupBy", "$year" },
        { "buckets", 4 }
    }),
};
PipelineDefinition<BsonDocument, BsonDocument> pipeline3 = PipelineDefinition<BsonDocument, BsonDocument>.Create(stages3);
AggregateFacet<BsonDocument, BsonDocument> aggregateFacet3 = AggregateFacet.Create("categorizedByYears(Auto)", pipeline3);

IAggregateFluent<AggregateFacetResults> aggregate = collection.Aggregate()
    .Facet(aggregateFacet1, aggregateFacet2, aggregateFacet3);

List<AggregateFacetResults> facetBsons = await aggregate.ToListAsync();

索引操作

  • 创建索引

    IMongoCollection<Student> collection = MongoDatabase.GetCollection<Student>();
    IndexKeysDefinition<Student> keys = Builders<Student>.IndexKeys.Ascending(student => student.Name);
    // 文字索引
    //IndexKeysDefinition<Student> keys = Builders<Student>.IndexKeys.Text(student => student.Name);
    // 哈希索引
    //IndexKeysDefinition<Student> keys = Builders<Student>.IndexKeys.Hashed(student => student.Name);
    CreateIndexOptions options = new()
    {
      Name = "Index_Name_ASC",
      // 是否是唯一索引
      //Unique = true,
    };
    CreateIndexModel<Student> createIndexModel = new(keys, options);
    string indexName = await collection.Indexes.CreateOneAsync(createIndexModel);
    
  • 创建复合索引

    IMongoCollection<Student> collection = MongoDatabase.GetCollection<Student>();
    IndexKeysDefinition<Student> studentClassIndex = Builders<Student>.IndexKeys.Ascending(student => student.StudentClass!.ClassId);
    IndexKeysDefinition<Student> studentNameIndex = Builders<Student>.IndexKeys.Ascending(student => student.Name);
    IndexKeysDefinition<Student> keys = Builders<Student>.IndexKeys.Combine(studentClassIndex, studentNameIndex);
    CreateIndexOptions options = new()
    {
      Name = "Index_ClassId_ASC_Name_ASC"
    };
    CreateIndexModel<Student> createIndexModel = new(keys, options);
    string indexName = await collection.Indexes.CreateOneAsync(createIndexModel);
    
  • 查询索引信息

    IMongoCollection<Student> collection = MongoDatabase.GetCollection<Student>();
    using IAsyncCursor<BsonDocument> cursor = await collection.Indexes.ListAsync();
    List<BsonDocument> bsons = await cursor.ToListAsync();
    
  • 删除指定索引或删除该集合全部索引

    IMongoCollection<Student> collection = MongoDatabase.GetCollection<Student>();
    // 删除指定名称的索引
    await collection.Indexes.DropOneAsync(name: "Index_Name_ASC");
    // 删除全部索引
    await collection.Indexes.DropAllAsync();
    

视图操作

  • 创建视图

    List<BsonDocument> stages = new();
    PipelineDefinition<BsonDocument, BsonDocument> pipeline = PipelineDefinition<BsonDocument, BsonDocument>.Create(stages);
    await MongoDatabase.CreateViewAsync(viewName: "StudentView", viewOn: "Student", pipeline);
    
  • 删除视图

    await MongoDatabase.DropCollectionAsync(name: "StudentView");
    

Spring Boot集成

emmm… Java随便应付一下得了😬

前提

  • 引入maven依赖
    • spring-boot-starter-data-mongodb
  • application.yml配置

    spring:
    data:
      mongodb:
        host: 192.168.73.133
        port: 27017
        database: db_student
    #      authentication-database:
    #      username:
    #      password:
    
  • 每个实体需用@MongoId注解标记为主键。

  • 装配事务管理器,单节点不支持事务,需搭建复制集。在需要使用的地方标记@Transactional注解即可。
    @Configuration
    public class MongoTran {
      @Bean
      public MongoTransactionManager transactionManager(MongoDatabaseFactory dbFactory) {
          return new MongoTransactionManager(dbFactory);
      }
    }
    

集合操作

  • 创建一个没有大小限制的集合,也是默认集合创建方式

    String collectionName = "student";
    if (!this.mongoTemplate.collectionExists(collectionName)) {
      MongoCollection<Document> collection =
              this.mongoTemplate.createCollection(collectionName);
    }
    // 获取集合名称列表
    Set<String> collectionNames = this.mongoTemplate.getCollectionNames();
    System.out.println(collectionNames);
    
  • 创建固定集合。固定集合是指有着固定大小的集合,当达到最大值时,它会自动覆盖最早的文档

    String collectionName = "student";
    if (!this.mongoTemplate.collectionExists(collectionName)) {
      CollectionOptions collectionOptions =
              CollectionOptions.empty()
                      .capped()
                      // 固定集合指定一个最大值(单位: kb)
                      .size(1024)
                      // 指定固定集合中包含文档的最大数量
                      .maxDocuments(100);
      MongoCollection<Document> collection =
              this.mongoTemplate.createCollection(collectionName, collectionOptions);
    }
    
  • 创建带数据校验的集合,在文件进行插入与更新时进行数据校验

    String collectionName = "student";
    if (!this.mongoTemplate.collectionExists(collectionName)) {
      // 设置验证条件,班级编号 0 < classId <= 20
      CriteriaDefinition criteria = Criteria.where("classId").gt(0).lte(20);
      // 设置集合选项验证对象
      CollectionOptions collectionOptions =
              CollectionOptions.empty()
                      .validator(Validator.criteria(criteria))
                      // 设置效验级别
                      .strictValidation()
                      // 设置效验不通过后执行的动作
                      .failOnValidationError();
      this.mongoTemplate.createCollection(collectionName, collectionOptions);
    }
    

文档操作

插入

  • 若新增数据的主键已经存在,则会抛异常提示主键重复,不保存当前数据

    StudentClass studentClass = new StudentClass();
    studentClass.setClassId(1).setClassName("向日葵班");
    Student student = new Student();
    student.setStudentId("064418118")
          .setStudentName("ble")
          .setBirthday(new Date())
          .setClassId(1)
          .setStudentClass(studentClass);
    String collectionName = "student";
    student = this.mongoTemplate.insert(student, collectionName);
    System.out.println(student);
    
  • 若新增数据的主键已经存在,则会对当前已经存在的数据进行修改操作

    StudentClass studentClass = new StudentClass();
    studentClass.setClassId(1).setClassName("向日葵班");
    Student student = new Student();
    student.setStudentId("064418118")
          .setStudentName("ble")
          .setBirthday(new Date())
          .setClassId(1)
          .setStudentClass(studentClass);
    String collectionName = "student";
    student = this.mongoTemplate.save(student, collectionName);
    System.out.println(student);
    
  • 批量新增

    StudentClass studentClass = new StudentClass();
    studentClass.setClassId(1).setClassName("向日葵班");
    List<Student> studentList = new ArrayList<>();
    for (int i = 1; i < 10; i++) {
      Student student = new Student();
      student.setStudentId("06441810" + i)
              .setStudentName(UUID.randomUUID().toString())
              .setBirthday(new Date())
              .setClassId(1)
              .setStudentClass(studentClass);
      studentList.add(student);
    }
    String collectionName = "student";
    Collection<Student> students = this.mongoTemplate.insert(studentList, collectionName);
    System.out.println(students);
    

    查询

  • 查询全部

    String collectionName = "student";
    List<Student> students = this.mongoTemplate.findAll(Student.class, collectionName);
    System.out.println(students);
    
  • 根据文档Id查询

    String collectionName = "student";
    String _id = "613395410deef60c763115c0";
    Student student = this.mongoTemplate.findById(_id, Student.class, collectionName);
    System.out.println(student);
    
  • 查询集合中,存在指定字段的文档数据

    String collectionName = "student";
    // 查询存在指定字段名称且值为1的文档数据
    Criteria criteria = Criteria.where("classId").exists(true).is(1);
    Query query = new Query(criteria);
    Student student = this.mongoTemplate.findOne(query, Student.class, collectionName);
    System.out.println(student);
    
  • 模糊查询

    String collectionName = "student";
    String input = "0644181";
    Criteria criteria = Criteria.where("classId").gte(1).lte(1);
    criteria.and("studentId").regex("^.*" + input + ".*$");
    Query query = new Query(criteria);
    List<Student> students = this.mongoTemplate.find(query, Student.class, collectionName);
    System.out.println(students);
    
  • 排序

    String collectionName = "student";
    Criteria criteria = Criteria.where("classId").is(1);
    Query query = new Query(criteria).with(Sort.by("birthday").descending());
    List<Student> students = this.mongoTemplate.find(query, Student.class, collectionName);
    System.out.println(students);
    
  • 分页

    String collectionName = "student";
    Criteria criteria = Criteria.where("classId").is(1);
    Query query = new Query(criteria).skip(0).limit(1);
    List<Student> students = this.mongoTemplate.find(query, Student.class, collectionName);
    System.out.println(students);
    
  • and关联多个条件

    String collectionName = "student";
    Criteria criteriaStudentName = Criteria.where("studentName").is("ble");
    Criteria criteriaClassId = Criteria.where("classId").is(1);
    Criteria criteria = new Criteria().andOperator(criteriaStudentName, criteriaClassId);
    Query query = new Query(criteria);
    List<Student> students = this.mongoTemplate.find(query, Student.class, collectionName);
    System.out.println(students);
    
  • or关联多个条件

    String collectionName = "student";
    Criteria criteriaStudentName = Criteria.where("studentName").is("ble");
    Criteria criteriaClassId = Criteria.where("classId").is(1);
    Criteria criteria = new Criteria().orOperator(criteriaStudentName, criteriaClassId);
    Query query = new Query(criteria);
    List<Student> students = this.mongoTemplate.find(query, Student.class, collectionName);
    System.out.println(students);
    
  • in查询

    String collectionName = "student";
    List<Integer> classIds = Arrays.asList(1, 2, 3);
    Criteria criteria = Criteria.where("classId").in(classIds);
    Query query = new Query(criteria);
    List<Student> students = this.mongoTemplate.find(query, Student.class, collectionName);
    System.out.println(students);
    
  • 查询符合条件的文档数量

    String collectionName = "student";
    Criteria criteria = Criteria.where("classId").is(1);
    Query query = new Query(criteria);
    long count = this.mongoTemplate.count(query, Student.class, collectionName);
    System.out.println(count);
    

更新

  • 更新查询到的第一个文档,如果没有找到就创建并插入一个新文档

    String collectionName = "student";
    Criteria criteria = Criteria.where("studentId").is("064418119");
    Query query = new Query(criteria);
    Update update = new Update().set("studentName", "xzz");
    UpdateResult upsert =
          this.mongoTemplate.upsert(query, update, Student.class, collectionName);
    System.out.println(upsert.getMatchedCount());
    
  • 更新查询到的第一个文档

    String collectionName = "student";
    Criteria criteria = Criteria.where("studentId").is("064418119");
    Query query = new Query(criteria);
    Update update = new Update().set("studentName", "qw");
    UpdateResult updateResult =
          this.mongoTemplate.updateFirst(query, update, Student.class, collectionName);
    System.out.println(updateResult.getMatchedCount());
    
  • 更新查询到的所有文档

    String collectionName = "student";
    Criteria criteria = Criteria.where("studentId").is("064418119");
    Query query = new Query(criteria);
    Update update = new Update().set("studentName", "ble");
    UpdateResult updateResult =
          this.mongoTemplate.updateMulti(query, update, Student.class, collectionName);
    System.out.println(updateResult.getMatchedCount());
    

删除

  • 删除集合中符合条件的一个或多个文档

    String collectionName = "student";
    Criteria criteria = Criteria.where("studentId").is("064418119");
    Query query = new Query(criteria);
    DeleteResult res = this.mongoTemplate.remove(query, collectionName);
    System.out.println(res.getDeletedCount());
    
  • 删除符合条件的第一个文档,并返回删除的文档

    String collectionName = "student";
    Criteria criteria = Criteria.where("studentId").is("064418119");
    Query query = new Query(criteria);
    Student delStudent = this.mongoTemplate.findAndRemove(query, Student.class, collectionName);
    System.out.println(delStudent);
    
  • 删除符合条件的全部文档,并返回删除的文档

    String collectionName = "student";
    Criteria criteria = Criteria.where("studentId").is("064418119");
    Query query = new Query(criteria);
    List<Student> delStudents =
          this.mongoTemplate.findAllAndRemove(query, Student.class, collectionName);
    System.out.println(delStudents);
    

管道操作

聚合管道操作符 含义
$project 可以从文档中选择想要的字段,和不想要的字段(指定的字段可以是来自输入文档或新计算字段的现有字段,也可以通过管道表达式进行一些复杂的操作,例如数学操作,日期操作,字符串操作,逻辑操作。
$match 用于过滤数据,只输出符合条件的文档。$match使用MongoDB的标准查询操作。
$limit 用来限制MongoDB聚合管道返回的文档数。
$skip 在聚合管道中跳过指定数量的文档,并返回余下的文档。
$unwind 将文档中的某一个数组类型字段拆分成多条,每条包含数组中的一个值。
$group 将集合中的文档分组,可用于统计结果。
$sort 将输入文档排序后输出。
  • 聚合函数相关

    String collectionName = "student";
    AggregationOperation group =
          // 根据班级编号分组
          Aggregation.group("classId")
                  // 班级中年龄最大的
                  .max("age")
                  .as("maxAge")
                  // 班级中年龄最小的
                  .min("age")
                  .as("minAge")
                  // 班级中学生的平均年龄
                  .avg("age")
                  .as("avgAge")
                  // 班级中所有学生的年龄总和
                  .sum("age")
                  .as("sumAge")
                  // 一共有多少个班级
                  .count()
                  .as("studentCount");
    Aggregation aggregation = Aggregation.newAggregation(group);
    AggregationResults<Map> results =
          this.mongoTemplate.aggregate(aggregation, collectionName, Map.class);
    results.getMappedResults().forEach(System.out::println);
    
  • 数据匹配过滤后进行聚合统计

    String collectionName = "student";
    AggregationOperation match = Aggregation.match(Criteria.where("classId").gt(0));
    AggregationOperation group = Aggregation.group("studentName").max("classId").as("max");
    Aggregation aggregation = Aggregation.newAggregation(match, group);
    AggregationResults<Map> results =
          this.mongoTemplate.aggregate(aggregation, collectionName, Map.class);
    results.getMappedResults().forEach(System.out::println);
    
  • 分组后排序

    String collectionName = "student";
    AggregationOperation sort = Aggregation.sort(Sort.by("classId").ascending());
    AggregationOperation group = Aggregation.group("studentName").min("classId").as("min");
    Aggregation aggregation = Aggregation.newAggregation(sort, group);
    AggregationResults<Map> results =
          this.mongoTemplate.aggregate(aggregation, collectionName, Map.class);
    results.getMappedResults().forEach(System.out::println);
    
  • 根据分组后的结果分页

    String collectionName = "student";
    AggregationOperation group = Aggregation.group("studentId");
    AggregationOperation skip = Aggregation.skip(1L);
    AggregationOperation limit = Aggregation.limit(1);
    Aggregation aggregation = Aggregation.newAggregation(group, skip, limit);
    AggregationResults<Map> results =
          this.mongoTemplate.aggregate(aggregation, collectionName, Map.class);
    results.getMappedResults().forEach(System.out::println);
    
  • 投影,控制需要显示的字段

    String collectionName = "student";
    AggregationOperation group =
          Aggregation.group("classId")
                  .max("age")
                  .as("maxAge")
                  .min("age")
                  .as("minAge")
                  .count()
                  .as("studentCount");
    AggregationOperation project = Aggregation.project("minAge", "studentCount");
    Aggregation aggregation = Aggregation.newAggregation(group, project);
    AggregationResults<Map> results =
          this.mongoTemplate.aggregate(aggregation, collectionName, Map.class);
    results.getMappedResults().forEach(System.out::println);
    
  • 获取每个组的包含某字段的文档的第一条或最后一条数据

    // 按照学生名称分组,查询每组每条文档包含classId字段的第一条文档
    String collectionName = "student";
    AggregationOperation group =
          Aggregation.group("studentName").first("classId").as("classIdFirst");
    Aggregation aggregation = Aggregation.newAggregation(group);
    AggregationResults<Map> results =
          this.mongoTemplate.aggregate(aggregation, collectionName, Map.class);
    results.getMappedResults().forEach(System.out::println);
    
  • 获取每组的某字段列表

    // 按照学生名称分组,获取每组的classId字段列表
    String collectionName = "student";
    AggregationOperation group =
          Aggregation.group("studentName").push("classId").as("classIdList");
    Aggregation aggregation = Aggregation.newAggregation(group);
    AggregationResults<Map> results =
          this.mongoTemplate.aggregate(aggregation, collectionName, Map.class);
    results.getMappedResults().forEach(System.out::println);
    
  • 将文档中的某一个数组类型字段拆分成多条,每组包含数组中的一个值

    String collectionName = "student";
    AggregationOperation group = Aggregation.project("studentName", "hobby");
    AggregationOperation unwind = Aggregation.unwind("hobby");
    Aggregation aggregation = Aggregation.newAggregation(group, unwind);
    AggregationResults<Map> results =
          this.mongoTemplate.aggregate(aggregation, collectionName, Map.class);
    results.getMappedResults().forEach(System.out::println);
    

索引操作

  • 创建升序索引

    String collectionName = "student";
    String indexName = "studentId";
    this.mongoTemplate.getCollection(collectionName).createIndex(Indexes.ascending(indexName));
    
  • 创建复合索引

    String collectionName = "student";
    String studentNameIndexName = "studentName";
    String classIdIndexName = "classId";
    this.mongoTemplate
          .getCollection(collectionName)
          .createIndex(Indexes.ascending(studentNameIndexName, classIdIndexName));
    
  • 创建文字索引

    String collectionName = "student";
    String indexName = "studentName";
    this.mongoTemplate.getCollection(collectionName).createIndex(Indexes.text(indexName));
    
  • 创建哈希索引

    String collectionName = "student";
    String indexName = "classId";
    this.mongoTemplate.getCollection(collectionName).createIndex(Indexes.hashed(indexName));
    
  • 创建唯一索引

    String collectionName = "student";
    String indexName = "birthday";
    IndexOptions options = new IndexOptions();
    options.unique(true);
    this.mongoTemplate
          .getCollection(collectionName)
          .createIndex(Indexes.ascending(indexName), options);
    
  • 创建局部索引

    String collectionName = "student";
    String indexName = "birthday";
    IndexOptions options = new IndexOptions();
    options.partialFilterExpression(Filters.exists(indexName, true));
    this.mongoTemplate
          .getCollection(collectionName)
          .createIndex(Indexes.ascending(indexName), options);
    
  • 获取所有索引信息

    String collectionName = "student";
    List<IndexInfo> indexInfo = this.mongoTemplate.indexOps(collectionName).getIndexInfo();
    System.out.println(indexInfo);
    
  • 删除指定索引

    String collectionName = "student";
    String indexName = "studentId";
    this.mongoTemplate.getCollection(collectionName).dropIndex(indexName);
    
  • 删除全部索引

    String collectionName = "student";
    this.mongoTemplate.getCollection(collectionName).dropIndexes();
    

    视图操作

  • 创建视图

    String viewName = "studentView";
    String collectionName = "student";
    if (!this.mongoTemplate.collectionExists(viewName)) {
      // 定义视图的管道,可设置视图显示的内容多个筛选条件
      List<Bson> pipeline = new ArrayList<>();
      // 设置条件,用于筛选集合中的文档数据,只有符合条件的才会映射到视图中
      pipeline.add(Document.parse("{'$match':{'classId':1}}"));
      this.mongoTemplate.getDb().createView(viewName, collectionName, pipeline);
    }
    
  • 删除视图

    String viewName = "studentView";
    if (this.mongoTemplate.collectionExists(viewName)) {
      this.mongoTemplate.getDb().getCollection(viewName).drop();
    }