本文旨在对于个人知识的梳理以及知识的分享,如果有不足的地方,欢迎大家在评论区指出
前提:本文只介绍Mongo中笔者经常用到的一些操作,对于连接等初始化相关操作不再赘述
CRUD操作
-
bson
bson.D{}
: 对文档的有序描述,key-value以逗号分隔
bson.M{}
: Map结构,key-value以冒号分隔,无序
bson.A{}
: 数组结构,元素要求是有序的文档描述,也就是bson.D{}的类型 -
相关操作
(1) InsertOneMongoDB.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
哪些地方有问题或者有什么需要补充地方,欢迎大佬们在评论区指出🤝