You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Golang中使用MongoDB的$mod操作符

在Golang中实现MongoDB的$mod查询操作符

在使用官方MongoDB Go驱动(go.mongodb.org/mongo-driver)时,你可以通过bson.M或bson.D两种方式构造对应$mod操作符的查询条件,完全匹配原生MongoDB查询语句{fieldName:{$mod:[24,0]}}。

方法1:使用bson.M(无序Map结构)

import (
    "context"
    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

func main() {
    // 假设已初始化MongoDB客户端
    client, _ := mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://localhost:27017"))
    defer client.Disconnect(context.TODO())

    // 构造$mod查询条件
    filter := bson.M{
        "fieldName": bson.M{
            "$mod": []int{24, 0},
        },
    }

    // 执行查询
    coll := client.Database("your_db_name").Collection("your_collection_name")
    cur, err := coll.Find(context.TODO(), filter)
    if err != nil {
        panic(err)
    }
    defer cur.Close(context.TODO())

    // 遍历并处理结果
    var results []bson.M
    if err := cur.All(context.TODO(), &results); err != nil {
        panic(err)
    }
}

方法2:使用bson.D(有序文档结构)

如果需要保证查询字段的顺序,可使用bson.D构造查询条件:

filter := bson.D{
    {Key: "fieldName", Value: bson.D{
        {Key: "$mod", Value: []int{24, 0}},
    }},
}

两种方式功能完全一致,根据是否需要维护字段顺序选择即可。

内容的提问来源于stack exchange,提问作者Jayabharathi Palanisamy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 18:32:21