gomog/manual/QUICK_REFERENCE.md

7.6 KiB

Gomog 快速参考手册

版本: v1.0.0-alpha
最后更新: 2026-03-14


📖 目录

  1. 常用命令速查
  2. 操作符速查表
  3. 聚合阶段速查表
  4. 数据类型映射
  5. 错误码速查

常用命令速查

HTTP API 基础

# 健康检查
curl http://localhost:8080/health

# 插入文档
curl -X POST http://localhost:8080/api/v1/{db}/{collection}/insert \
  -H "Content-Type: application/json" \
  -d '{"documents": [{...}]}'

# 查询文档
curl -X POST http://localhost:8080/api/v1/{db}/{collection}/find \
  -H "Content-Type: application/json" \
  -d '{"filter": {...}}'

# 更新文档
curl -X POST http://localhost:8080/api/v1/{db}/{collection}/update \
  -H "Content-Type: application/json" \
  -d '{"filter": {...}, "update": {...}}'

# 删除文档
curl -X POST http://localhost:8080/api/v1/{db}/{collection}/delete \
  -H "Content-Type: application/json" \
  -d '{"filter": {...}}'

# 聚合管道
curl -X POST http://localhost:8080/api/v1/{db}/{collection}/aggregate \
  -H "Content-Type: application/json" \
  -d '{"pipeline": [...]}'

MongoDB Shell

// 连接
mongosh --host localhost --port 27017

// 基本 CRUD
db.collection.insertOne({field: "value"})
db.collection.find({field: {$gt: 10}})
db.collection.updateOne({field: 1}, {$set: {field: 2}})
db.collection.deleteOne({field: 1})

// 聚合
db.collection.aggregate([
  {$match: {status: "active"}},
  {$group: {_id: "$category", count: {$sum: 1}}}
])

操作符速查表

比较操作符

操作符 说明 示例
$eq 等于 {"age": {"$eq": 18}}
$ne 不等于 {"status": {"$ne": "deleted"}}
$gt 大于 {"price": {"$gt": 100}}
$gte 大于等于 {"score": {"$gte": 60}}
$lt 小于 {"quantity": {"$lt": 10}}
$lte 小于等于 {"age": {"$lte": 65}}
$in 在数组中 {"status": {"$in": ["a","b"]}}
$nin 不在数组中 {"type": {"$nin": ["x","y"]}}

逻辑操作符

操作符 说明 示例
$and {"$and": [{a:1}, {b:2}]}
$or {"$or": [{a:1}, {b:2}]}
$not {"price": {"$not": {"$gt": 100}}}
$nor 或非 {"$nor": [{a:1}, {b:2}]}

元素操作符

操作符 说明 示例
$exists 字段存在 {"email": {"$exists": true}}
$type 类型检查 {"age": {"$type": "int"}}

数组操作符

操作符 说明 示例
$all 包含所有 {"tags": {"$all": ["a","b"]}}
$elemMatch 元素匹配 {"scores": {"$elemMatch": {"$gt": 80}}}
$size 数组大小 {"items": {"$size": 5}}

更新操作符

操作符 说明 示例
$set 设置字段 {"$set": {name: "test"}}
$unset 移除字段 {"$unset": {oldField: ""}}
$inc 递增 {"$inc": {count: 1}}
$mul 乘法 {"$mul": {price: 0.9}}
$push 推入数组 {"$push": {tags: "new"}}
$pull 拉出数组 {"$pull": {tags: "old"}}
$addToSet 添加到集合 {"$addToSet": {ids: 123}}
$pop 弹出元素 {"$pop": {items: 1}}

聚合阶段速查表

数据过滤

阶段 说明 示例
$match 过滤文档 {$match: {status: "active"}}
$limit 限制数量 {$limit: 10}
$skip 跳过数量 {$skip: 20}
$sample 随机采样 {$sample: {size: 5}}
$bucket 分桶分组 {$bucket: {groupBy: "$price", boundaries: [0,100]}}

数据转换

阶段 说明 示例
$project 重塑文档 {$project: {name: 1, _id: 0}}
$addFields 添加字段 {$addFields: {total: {$add: ["$a","$b"]}}}
$unset 移除字段 {$unset: ["temp"]}
$replaceRoot 替换根文档 {$replaceRoot: {newRoot: "$user"}}

数据分组

阶段 说明 示例
$group 分组聚合 {$group: {_id: "$dept", avg: {$avg: "$salary"}}}
$sort 排序 {$sort: {createdAt: -1}}
$sortByCount 分组计数 {$sortByCount: "$category"}

关联查询

阶段 说明 示例
$lookup 左外连接 {$lookup: {from: "orders", localField: "_id", foreignField: "userId", as: "orders"}}
$graphLookup 递归查找 {$graphLookup: {from: "orgs", startWith: "$parentId", connectFromField: "_id", connectToField: "parentId", as: "subOrgs"}}
$unwind 展开数组 {$unwind: "$tags"}

性能优化

阶段 说明 示例
$facet 多面聚合 {$facet: {data: [...], stats: [...]}}
$indexStats 索引统计 {$indexStats: {}}
$setWindowFields 窗口函数 {$setWindowFields: {partitionBy: "$region", output: {rank: {$documentNumber: {}}}}}

累加器

操作符 说明 示例
$sum 求和 {total: {$sum: "$amount"}}
$avg 平均值 {avg: {$avg: "$score"}}
$min 最小值 {min: {$min: "$price"}}
$max 最大值 {max: {$max: "$quantity"}}
$push 推入数组 {items: {$push: "$$ROOT"}}
$addToSet 添加到集合 {unique: {$addToSet: "$tag"}}
$first 第一个值 {first: {$first: "$name"}}
$last 最后一个值 {last: {$last: "$value"}}
$count 计数 {cnt: {$count: {}}}

数据类型映射

BSON 类型对应表

BSON 类型 JavaScript Go Python SQL
String String string str VARCHAR
Int32 Number int32 int INTEGER
Int64 BigInt int64 int BIGINT
Double Number float64 float DOUBLE
Boolean Boolean bool bool BOOLEAN
Null null nil None NULL
Array Array []interface{} list JSONB
Object Object map[string]interface{} dict JSONB
Date Date time.Time datetime DATETIME
ObjectId ObjectId primitive.ObjectID ObjectId VARCHAR(24)

错误码速查

常见错误码

错误码 错误名称 说明
1 InternalError 内部错误
2 BadValue 参数值错误
7 NoSuchKey 键不存在
11000 DuplicateKey 重复键值
26 NamespaceNotFound 集合不存在
43 NamespaceExists 集合已存在
52 InvalidPipelineOperator 无效的聚合操作符

HTTP 状态码

状态码 说明
200 成功
400 请求参数错误
404 资源不存在
500 服务器内部错误

配置文件示例

server:
  http_addr: ":8080"
  tcp_addr: ":27017"
  mode: "dev"

database:
  type: "sqlite"
  dsn: "gomog.db"
  max_open: 10
  max_idle: 5

log:
  level: "info"
  format: "text"

环境变量

变量 配置项 默认值
GOMOG_HTTP_ADDR server.http_addr :8080
GOMOG_TCP_ADDR server.tcp_addr :27017
GOMOG_DB_TYPE database.type sqlite
GOMOG_DB_DSN database.dsn gomog.db
GOMOG_LOG_LEVEL log.level info

相关链接


维护者: Gomog Team
许可证: MIT