feat: database.

This commit is contained in:
Bobo
2025-06-29 09:29:47 +08:00
parent d0e55cf372
commit 29a8782662
22 changed files with 1481 additions and 109 deletions

View File

@@ -50,8 +50,6 @@ const (
OperatorInc = "$inc" // 增加值
OperatorMul = "$mul" // 乘法
OperatorRename = "$rename" // 重命名字段
OperatorMin = "$min" // 设置最小值
OperatorMax = "$max" // 设置最大值
OperatorCurrentDate = "$currentDate" // 设置当前日期
OperatorAddToSet = "$addToSet" // 添加到集合
OperatorPop = "$pop" // 删除数组中的元素
@@ -81,6 +79,23 @@ const (
OperatorIndexStats = "$indexStats" // 索引统计
OperatorOut = "$out" // 输出
OperatorMerge = "$merge" // 合并
OperatorSum = "$sum" // 求和
OperatorAvg = "$avg" // 平均值
OperatorMin = "$min" // 最小值
OperatorMax = "$max" // 最大值
OperatorFirst = "$first" // 第一个值
OperatorLast = "$last" // 最后一个值
OperatorStdDevPop = "$stdDevPop" // 总体标准差
OperatorStdDevSamp = "$stdDevSamp" // 样本标准差
// 类型转换操作符
OperatorToLong = "$toLong" // 转换为 long 类型
OperatorToDouble = "$toDouble" // 转换为 double 类型
OperatorToDecimal = "$toDecimal" // 转换为 decimal 类型
OperatorToString = "$toString" // 转换为 string 类型
OperatorToDate = "$toDate" // 转换为 date 类型
OperatorToInt = "$toInt" // 转换为 int 类型
// 地理空间操作符

View File

@@ -10,7 +10,7 @@ require (
github.com/go-kratos/kratos/v2 v2.8.4
github.com/stretchr/testify v1.10.0
github.com/tx7do/go-utils v1.1.29
github.com/tx7do/kratos-bootstrap/api v0.0.26
github.com/tx7do/kratos-bootstrap/api v0.0.27
go.mongodb.org/mongo-driver/v2 v2.2.2
google.golang.org/protobuf v1.36.6
)

View File

@@ -6,8 +6,9 @@ import (
)
type QueryBuilder struct {
filter bsonV2.M
opts *optionsV2.FindOptions
filter bsonV2.M
opts *optionsV2.FindOptions
pipeline []bsonV2.M
}
func NewQuery() *QueryBuilder {
@@ -211,6 +212,17 @@ func (qb *QueryBuilder) SetPage(page, size int64) *QueryBuilder {
return qb
}
// AddStage 添加聚合阶段到管道
func (qb *QueryBuilder) AddStage(stage bsonV2.M) *QueryBuilder {
qb.pipeline = append(qb.pipeline, stage)
return qb
}
// BuildPipeline 返回最终的聚合管道
func (qb *QueryBuilder) BuildPipeline() []bsonV2.M {
return qb.pipeline
}
// Build 返回最终的过滤条件和查询选项
func (qb *QueryBuilder) Build() (bsonV2.M, *optionsV2.FindOptions) {
return qb.filter, qb.opts

View File

@@ -217,3 +217,22 @@ func TestSetNearSphere(t *testing.T) {
assert.Equal(t, expected, qb.filter[field])
}
func TestQueryBuilderPipeline(t *testing.T) {
// 创建 QueryBuilder 实例
qb := NewQuery()
// 添加聚合阶段
matchStage := bsonV2.M{OperatorMatch: bsonV2.M{"status": "active"}}
groupStage := bsonV2.M{OperatorGroup: bsonV2.M{"_id": "$category", "count": bsonV2.M{OperatorSum: 1}}}
sortStage := bsonV2.M{OperatorSortAgg: bsonV2.M{"count": -1}}
qb.AddStage(matchStage).AddStage(groupStage).AddStage(sortStage)
// 构建 Pipeline
pipeline := qb.BuildPipeline()
// 验证 Pipeline
expectedPipeline := []bsonV2.M{matchStage, groupStage, sortStage}
assert.Equal(t, expectedPipeline, pipeline)
}