【Golang】MongoDB相关操作集锦

本文旨在对于个人知识的梳理以及知识的分享,如果有不足的地方,欢迎大家在评论区指出


前提:本文只介绍Mongo中笔者经常用到的一些操作,对于连接等初始化相关操作不再赘述


CRUD操作
  1. bson
    bson.D{}: 对文档的有序描述,key-value以逗号分隔
    bson.M{}: Map结构,key-value以冒号分隔,无序
    bson.A{}: 数组结构,元素要求是有序的文档描述,也就是bson.D{}的类型

  2. 相关操作
    (1) InsertOne

    MongoDB.Collections("表名").InsertOne(c, bson.M{"name": "jhd", "age": 12}) 
    

    (2) InsertMany

    result := make([]interface{}, 0) // 声明接口list,用于承接所有要插入的数据
    for _, value := range models {
    	result = append(result, value)
    }
    MongoDB.Collections("表名").InsertMany(c, result)
    

    (3) Find(c context.Context, match-查询条件, opt-可以指定排序顺序以及limit和offset等)

    result := make([]自定义的model类, 0)
    match := bson.D{
    	{Key: "name", Value: "jhd"},
    	{Key: "pwd", Value: "123"},
    }
    cursor, err := MongoDB.Collections("表名").Find(c, match)
    err = cursor.All(c, &result) // cursor是一个游标,可以通过它来获取所有的元素
    // 此时result就承接了所有的元素
    

    (4) UpdateOne(c context.Context, where-指定查询条件, set-指要更新的字段)

    where := bson.D{
    	// 拼接查询条件
    }
    toSet := bson.M{
    	// 指定要更新的字段
    }
    MongoDB.Collections("表名").UpdateOne(c, where, bson.M{"$set": toSet})
    

    (5) UpdateMany(与UpdateOne的使用方式基本一致)
    (6) DeleteOne, DeleteMany(c context.Context, where, opt-可以指定删除的时候的一些准则,例如可以指定忽略大小写)
    (7) Distanct

    // 返回所有不同的人名
    distinctValues, err := MongoDB.Collections("表名").Distinct(ctx, "name", bson.M{})
    

    (8) Count(c context.Context, where) 用于获得指定条件的记录行数

    where := bson.D{
    // 查询条件
    }
    num, err := MongoDB.Collections("表名").CountDocument(c, where)
    

    (9) Aggregate

    MongoDB.Collections("表名").aggregate([{$group: {_id:null, count: {$sum:1}}}])
    
    相当于mysql:
    select count(*) as count from "表名"
    
    
    MongoDB.Collections("表名").aggregate(
    	[{$match:{status:'A'}}, 
    	{$group: 
    		{_id: "$cust_id", 
    		total: {$sum: "$price"}}
    	},
    	{$match: {total: {$gt: 250}}}
    	])
    	
    相当于mysql:
    select cust_id, sum(price) as total
    from "表名"
    where status = 'A'
    group by cust_id
    having total > 250
    

哪些地方有问题或者有什么需要补充地方,欢迎大佬们在评论区指出🤝

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值