使用rust操作mongodb

准备工作 使用rust进行mongodb连接需要添加依赖,在Cargo.toml中添加下面的依赖 [dependencies] mongodb="2" serde = "1" 添加serde的原因是我们建模的时候需要用。 预备知识 连接数据库 下面是我们的本地数据库连接 const CONNECT_STR:&str = "mongodb://czyt:czyt@192.168.1.21:27017"; 然后使用连接字符串进行数据库连接 let mut client_options = ClientOptions::parse_async(CONNECT_STR).await?; // Set the server_api field of the client_options object to Stable API version 1 let server_api = ServerApi::builder() .version(ServerApiVersion::V1) .build(); client_options.server_api = Some(server_api); // Create a new client and connect to the server let client = Client::with_options(client_options)?; // Send a ping to confirm a successful connection client.database("admin").run_command(doc! { "ping": 1 }, None).await?; println!("Pinged your deployment. You successfully connected to MongoDB!"); Ok(()) 数据库建模 您可以使用任何实现 serde 包中的 Serialize 和 Deserialize 特征的 Rust 数据类型作为 Collection 的泛型类型参数实例。要实现 Serialize 和 Deserialize 特征,您必须在定义 Rust 类型之前包含以下 derive 属性: ...

2024-04-15 · 9 分钟 · czyt

为Mongodb安装Percona Monitoring and Management

Percona Monitoring and Management (PMM) 是一种开源数据库可观察性、监控和管理工具,可与 MySQL、PostgreSQL、MongoDB 及其运行的服务器一起使用。它使您能够在一个位置查看所有数据库的节点到单个查询的性能指标。通过查询分析,您可以快速找到成本高昂且运行缓慢的查询以解决瓶颈。此外,Percona Advisors 为您提供性能、安全性和配置建议,帮助您保持数据库保持最佳性能。备份、恢复和内置开源私有 DBaaS 等警报和管理功能旨在提高 IT 团队的工作速度。 软件安装 安装环境为Ubuntu 22.04,下面的步骤参考了Percona官网的安装文档 安装服务端 本安装需要Docker环境,如果当前机器没有安装Docker,脚本会自动进行安装 使用下面命令安装 curl -fsSL https://www.percona.com/get/pmm | /bin/bash 或者 curl -fsSL https://www.percona.com/get/pmm | /bin/bash 安装完毕以后,请稍等片刻会显示server的访问信息 Gathering/downloading required components, this may take a moment Checking docker installation - installed. Starting PMM server... Created PMM Data Volume: pmm-data Created PMM Server: pmm-server Use the following command if you ever need to update your container by hand: docker run -d -p 443:443 --volumes-from pmm-data --name pmm-server --restart always percona/pmm-server:2 PMM Server has been successfully setup on this system! You can access your new server using one of the following web addresses: https://172.17.0.1:443/ https://127.0.0.1:443/ https://10.10.31.19:443/ The default username is 'admin' and the password is 'admin' :) Note: Some browsers may not trust the default SSL certificate when you first open one of the urls above. If this is the case, Chrome users may want to type 'thisisunsafe' to bypass the warning. Enjoy Percona Monitoring and Management! 这时就可以通过web登录了,第一次登录会要求修改密码。 ...

2023-11-18 · 2 分钟 · czyt

从Golang的开源项目中学习不同的功能实现

缘起 最近看到有些go开源项目中的代码,看到其中的功能,故整理备用。 密码 阈值解密(Threshold Decryption) 来源 取自公众号文章 package main import ( "crypto/rand" "fmt" "github.com/hashicorp/vault/shamir" ) func main() { // 1. 生成一个随机密钥(如AES-256密钥) secretKey := make([]byte, 32) _, err := rand.Read(secretKey) if err != nil { panic(err) } fmt.Printf("原始密钥: %x\n", secretKey) // 2. 分片为3份,至少需要2份恢复(阈值k=2,总分片n=3) shards, err := shamir.Split(secretKey, 3, 2) if err != nil { panic(err) } // 3. 模拟分片存储(实际中分发给不同机构) shard1, shard2, shard3 := shards[0], shards[1], shards[2] fmt.Printf("分片1: %x\n分片2: %x\n分片3: %x\n", shard1, shard2, shard3) // 4. 恢复密钥(任意2个分片) recoveredKey, err := shamir.Combine([][]byte{shard1, shard2}) // 使用分片1和2 if err != nil { panic(err) } fmt.Printf("恢复的密钥: %x\n", recoveredKey) } 数据结构 优先级队列 项目 https://github.com/tigrisdata/tigris ...

2022-11-25 · 62 分钟 · czyt

在Alibaba Cloud Linux上安装MongoDB

安装步骤 查询系统版本 执行命令lsb_release -a返回下面的内容 LSB Version: :core-4.1-amd64:core-4.1-noarch Distributor ID: AlibabaCloud Description: Alibaba Cloud Linux release 3 (Soaring Falcon) Release: 3 Codename: SoaringFalcon 添加yum源 创建repo文件etc/yum.repos.d/mongodb.repo并输入下面的内容,这里安装的mongodb版本为6.0,其他版本请参考官网 (配置偶数版本,奇数版不适合生产使用)。 官网的配置文件如下: [mongodb-org-6.0] name=MongoDB Repository baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/6.0/x86_64/ gpgcheck=1 enabled=1 gpgkey=https://www.mongodb.org/static/pgp/server-6.0.asc 使用这个配置文件是安装不了的,需要修改$releasever为相应的版本,Alibaba Cloud Linux 3修改为8 (设置一个releasever的环境变量也许也可以,没有验证。)即可。即下面的样子 [mongodb-org-6.0] name=MongoDB Repository baseurl=https://repo.mongodb.org/yum/redhat/8/mongodb-org/6.0/x86_64/ gpgcheck=1 enabled=1 gpgkey=https://www.mongodb.org/static/pgp/server-6.0.asc 使用命令 yum -y install mongodb-org 安装即可。另外阿里云也提供了国内的镜像源,上面的配置文件可以修改为下面的内容,也是等效的。 [mongodb-org-6.0] name=MongoDB Repository baseurl=http://mirrors.aliyun.com/mongodb/yum/redhat/8/mongodb-org/6.0/x86_64/ gpgcheck=1 enabled=1 gpgkey=https://www.mongodb.org/static/pgp/server-6.0.asc 参考链接 如何在Alibaba Cloud Linux 3上安装MongoDB 5.0

2022-08-30 · 1 分钟 · czyt

Golang MongoDB ODM mgm使用

(本文大部分内容根据官方文档翻译而来) 环境准备 golang 1.10+ mongodb mgm 模型定义 定义 定义模型 type Book struct { // DefaultModel adds _id, created_at and updated_at fields to the Model mgm.DefaultModel `bson:",inline"` Name string `json:"name" bson:"name"` Pages int `json:"pages" bson:"pages"` } func NewBook(name string, pages int) *Book { return &Book{ Name: name, Pages: pages, } } mgm 在创建表时会自动检测Model生成的Collection名称 book:=Book{} // Print your model collection name. collName := mgm.CollName(&book) fmt.Println(collName) // 打印: books 如果要自定义生成Collection的名称。需要实现CollectionNameGetter接口。 ...

2022-05-31 · 7 分钟 · czyt

MongoDB操作指北

TL;DR 环境准备 mongoDB 预备知识 MongoDB常见的数据类型 数据类型 示例 说明 Null {"x" : null} Boolean {"x" : true} Number {"x" : 3.14} {"x" : 3} {"x" : NumberInt("3")} {"x" : NumberLong("3")} 默认64位浮点数,整数需要使用NumberInt和NumberLong String {"x" : "foobar"} 编码格式为UTF-8 Date {"x" : new Date()} 64位时间戳(从January 1, 1970),不存时区。通过new Date()进行调用。 Regular expression {"x" : /foobar/i} javascript 正则 Array {"x" : ["a", "b", "c"]} Embedded document {"x" : {"foo" : "bar"}} Object ID {"x" : ObjectId()} 文档12字节的ID Binary data 一个任意字节的字符串。是保存非UTF-8字符串到数据库的唯一方法。 Code {"x" : function() { /* ... */ }} 数据操作 数据库连接 连接字符串 MongoDB的连接字符串为如下格式 ...

2022-05-26 · 12 分钟 · czyt

Rasp3b 安装MongoDB

安装 机器安装的是Manjaro,所以本文介绍的是Manjaro的树莓派3安装方式 ➜ ~ screenfetch czyt@** OS: Manjaro-ARM 22.01 Kernel: aarch64 Linux 5.15.24-1-MANJARO-ARM-RPI ##### Uptime: 21d 21h 58m ####### Packages: Unknown ##O#O## Shell: zsh 5.8.1 ####### Disk: 11G / 118G (9%) ########### CPU: BCM2835 @ 4x 1.2GHz ############# GPU: ############### RAM: 248MiB / 919MiB ################ ################# ##################### ##################### ################# 使用命令 yay -S mongodb44-bin进行安装,安装完毕后 启用服务 systemctl enable mongodb 检查服务状态 systemctl status mongodb ● mongodb.service - MongoDB Database Server Loaded: loaded (/usr/lib/systemd/system/mongodb.service; enabled; vendor preset: disabled) Active: active (running) since Wed 2022-03-23 13:11:08 CST; 11s ago Docs: https://docs.mongodb.org/manual Main PID: 624895 (mongod) CPU: 2.610s CGroup: /system.slice/mongodb.service └─624895 /usr/bin/mongod --config /etc/mongodb.conf 常见问题 非法指令 (核心已转储) 启动服务报错 非法指令 (核心已转储)英文系统可能是(Illegal instruction(core dumped)) 开始使用的是 yay -S mongodb-bin进行安装,后搜索官方论坛发现是官方打包的时候默认使用了最新架构,但是树莓派是老设备,可能不支持部分指令,换成上文的指令安装4.x版本后解决。 ...

2022-03-23 · 2 分钟 · czyt