当前位置:网站首页>golang使用mongo-driver操作——查(基础)
golang使用mongo-driver操作——查(基础)
2022-06-27 21:10:00 【lsjweiyi】
不管任何数据库,查都是最复杂的操作。
基本查询,并且解析成结构体:
// 最基本的查询,一个查询条件即可,参考:https://www.mongodb.com/docs/manual/tutorial/query-documents/
func Find(mongo *mongo.Database, ctx context.Context) {
baseAdd := create.BaseAdd{
}
filter := bson.M{
} // 空结构体匹配所有
// 查询数据,并解析成结构体
err := mongo.Collection("test").FindOne(ctx, filter).Decode(&baseAdd)
if err != nil {
fmt.Println("err")
}
fmt.Println(baseAdd)
}
匹配多个值,且解析成结构体数组:
// 用$in关键字查询有多个值的情况
func FindIn(mongo *mongo.Database, ctx context.Context) {
filter := bson.M{
"int32": bson.M{
"$in": bson.A{
math.MaxInt32, math.MaxInt32 - 1}}}
cur, err := mongo.Collection("test").Find(ctx, filter)
if err != nil {
fmt.Println("err")
}
// 多个文档解析程数组的方法
var baseAdd []create.BaseAdd
err = cur.All(ctx, &baseAdd)
fmt.Println(err)
fmt.Println(baseAdd)
}
大于和等于的匹配查询,并遍历结果:
// 用gt和lt关键字查询大于和小于,后面加个e表示等于
func FindGteAndLte(mongo *mongo.Database, ctx context.Context) {
// 多个条件是隐式的and关系,表示要同时满足全部条件
filter := bson.M{
"int32": bson.M{
"$gte": math.MaxInt32 - 1, "$lt": math.MaxInt32}}
cur, err := mongo.Collection("test").Find(ctx, filter)
if err != nil {
fmt.Println("err")
}
// 遍历数据
for cur.TryNext(ctx) {
result, _ := cur.Current.Elements()
fmt.Println(result)
}
cur.Close(ctx)
}
通常我们查询条件都是隐式and关系,可以使用or关键字表示多个条件只需满足其一:
// or对应的是个数组,只要满足数组里任一条件都可
filter := bson.M{
"$or": bson.A{
bson.M{
"int32": bson.M{
"$gte": math.MaxInt32 - 1}}, bson.M{
"int32": bson.M{
"$lt": math.MaxInt32}}}}
嵌套字段的查询匹配:
filter := bson.M{
"object.id": 2} // 直接用点连接就好,没什么区别
之前的查询我们都是返回所有字段,还可以选择查询指定字段:
// 1表示只查询id字段,但是,主键_id会默认查询出来
options := options.FindOptions{
Projection: bson.M{
"id": 1}}
// 所以还可以加上"_id": 0排除主键
options := options.FindOptions{
Projection: bson.M{
"id": 1, "_id": 0}}
与上面相反,可以指定一个字段不要,查询剩余字段:
// 排除_id,其他字段都会被查出来,可以排除多个
options := options.FindOptions{
Projection: bson.M{
"_id": 0}}
对于嵌套的文档也同样受用,且用LookupErr遍历时,仅获取想要的key值:
// 对于嵌套的文档也同样受用
func FindChildField(mongo *mongo.Database, ctx context.Context) {
filter := bson.M{
} // 空结构体匹配所有
// 嵌套字段也一样这么查
options := options.FindOptions{
Projection: bson.M{
"object.id": 1, "_id": 0}}
cur, err := mongo.Collection("test").Find(ctx, filter, &options)
if err != nil {
fmt.Println("err")
}
// 遍历数据
for cur.TryNext(ctx) {
result, _ := cur.Current.LookupErr("object")
fmt.Println(result)
}
cur.Close(ctx)
}
边栏推荐
- 【剑指Offer】48. 最长不含重复字符的子字符串
- [electron] basic learning
- 【PCL自学:Segmentation4】基于Min-Cut点云分割
- ClickOnce error deploying ClickOnce application - the reference in the manifest does not match the identity of the downloaded assembly
- Halcon's region: features of multiple regions (6)
- C language character pointer and string initialization
- Typora 1.2.5等版本下载
- Fsnotify interface of go language to monitor file modification
- How vivado adds timing constraints
- 【蓝桥杯集训100题】scratch数字计算 蓝桥杯scratch比赛专项预测编程题 集训模拟练习题第16题
猜你喜欢

图的存储结构

使用SQL进行数据去重的N种方法

Discuz小鱼游戏风影传说商业GBK+UTF8版模板/DZ游戏网站模板

The file or assembly 'cefsharp.core.runtime.dll' or one of its dependencies could not be loaded. Is not a valid Win32 Application. (exception from hresult:0x800700c1)

Golang - the difference between new and make

小程序referer

This year's examinees are more "desperate" than the college entrance examination

EasyCVR平台路由日志功能的技术实现过程【附代码】

How to set the enterprise wechat group robots to send messages regularly?

golang - new和make的区别
随机推荐
【AI应用】NVIDIA GeForce RTX 3060的详情参数
The choice and trade-off between vector recall and literal recall
使用cef3开发的浏览器不支持flash问题的解决
Online JSON to plaintext tool
Classification of cifar-10 dataset with pytorch
Advertising is too "wild", Yoshino "surrenders"
ICML 2022: UFRGS |作为最优策略转移基础的乐观线性支持和后继特征
Ice cream or snow "high"?
第一性原理(最优解理论)
【剑指Offer】47. 礼物的最大价值
halcon之区域:多种区域(Region)特征(6)
量化交易入门教程
6G显卡显存不足出现CUDA Error:out of memory解决办法
Introduction to quantitative trading
新加坡国立大学|采用无模型强化学习方法评估能源效益数据中心的节能情况
最新云开发微信余额充电器特效小程序源码
Cornernet由浅入深理解
clickonce 部署ClickOnce应用程序时出错-清单中的引用与下载的程序集的标识不匹配
【PCL自学:Segmentation3】基于PCL的点云分割:区域增长分割
EasyCVR平台路由日志功能的技术实现过程【附代码】