当前位置:网站首页>Golang uses Mongo driver operation - query (basic)
Golang uses Mongo driver operation - query (basic)
2022-06-27 23:43:00 【lsjweiyi】
Regardless of any database , Checking is the most complicated operation .
The basic query , And it is resolved into a structure :
// The most basic query , One query condition is enough , Reference resources :https://www.mongodb.com/docs/manual/tutorial/query-documents/
func Find(mongo *mongo.Database, ctx context.Context) {
baseAdd := create.BaseAdd{
}
filter := bson.M{
} // Empty structure matches all
// Query data , And parse it into a structure
err := mongo.Collection("test").FindOne(ctx, filter).Decode(&baseAdd)
if err != nil {
fmt.Println("err")
}
fmt.Println(baseAdd)
}
Match multiple values , And it is parsed into a structure array :
// use $in Keyword query has multiple values
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")
}
// Methods for parsing multiple document arrays
var baseAdd []create.BaseAdd
err = cur.All(ctx, &baseAdd)
fmt.Println(err)
fmt.Println(baseAdd)
}
Matching queries greater than and equal to , And traverse the results :
// use gt and lt Keyword query greater than and less than , Add a e Is equal to
func FindGteAndLte(mongo *mongo.Database, ctx context.Context) {
// Multiple conditions are implicit and Relationship , It means that all conditions must be met at the same time
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")
}
// Traversal data
for cur.TryNext(ctx) {
result, _ := cur.Current.Elements()
fmt.Println(result)
}
cur.Close(ctx)
}
Usually our query conditions are implicit and Relationship , have access to or Keyword indicates that only one of several conditions needs to be satisfied :
// or The corresponding is an array , As long as any condition in the array is satisfied
filter := bson.M{
"$or": bson.A{
bson.M{
"int32": bson.M{
"$gte": math.MaxInt32 - 1}}, bson.M{
"int32": bson.M{
"$lt": math.MaxInt32}}}}
Query matching of nested fields :
filter := bson.M{
"object.id": 2} // Just connect directly with points , No difference
In the previous queries, we returned all fields , You can also choose to query the specified fields :
// 1 Means only query id Field , however , Primary key _id It will be queried by default
options := options.FindOptions{
Projection: bson.M{
"id": 1}}
// So we can add "_id": 0 Exclude primary key
options := options.FindOptions{
Projection: bson.M{
"id": 1, "_id": 0}}
Contrary to the above , You can specify a field not to , Query remaining fields :
// exclude _id, All other fields will be found , Multiple... Can be excluded
options := options.FindOptions{
Projection: bson.M{
"_id": 0}}
The same is true for nested documents , And use LookupErr Ergodic time , Just get what you want key value :
// The same is true for nested documents
func FindChildField(mongo *mongo.Database, ctx context.Context) {
filter := bson.M{
} // Empty structure matches all
// The same is true for nested fields
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")
}
// Traversal data
for cur.TryNext(ctx) {
result, _ := cur.Current.LookupErr("object")
fmt.Println(result)
}
cur.Close(ctx)
}
边栏推荐
- Const keyword and its function (usage), detailed explanation of C language const
- 第 2 章 集成 MP
- Technical implementation process of easycvr platform routing log function [code attached]
- C language character pointer and string initialization
- 打造南沙“强芯”,南沙首届IC Nansha大会召开
- 使用cef3开发的浏览器不支持flash问题的解决
- pytorch实现kaggle猫狗识别
- Detect objects and transfer images through mqtt
- Swing UI container (I)
- Feign通过自定义注解实现路径的转义
猜你喜欢

ClickOnce error deploying ClickOnce application - the reference in the manifest does not match the identity of the downloaded assembly

golang - new和make的区别

【蓝桥杯集训100题】scratch数字计算 蓝桥杯scratch比赛专项预测编程题 集训模拟练习题第16题

Cornernet understands from simple to profound

零基础自学SQL课程 | IF函数

Prediction of benign / malignant breast tumors (logistic regression classifier)

How vivado adds timing constraints

Working at home is more tiring than going to work at the company?

【PCL自学:Segmentation4】基于Min-Cut点云分割

零基础自学SQL课程 | CASE函数
随机推荐
企业架构师面试的100个问题
clickonce 部署ClickOnce应用程序时出错-清单中的引用与下载的程序集的标识不匹配
2022年PMP项目管理考试敏捷知识点(3)
【AI应用】NVIDIA Tesla V100-PCIE-32GB的详情参数
Working at home is more tiring than going to work at the company?
小程序referer
vivado VIO IP的用法
Stream + Nacos
ASP.NET仓库进销存ERP管理系统源码 ERP小程序源码
Vivado FFT IP的使用说明
Swing UI——容器(一)
halcon之区域:多种区域(Region)特征(6)
Storage structure of graph
Cornernet由浅入深理解
Detect objects and transfer images through mqtt
Discuz small fish game wind shadow legend business gbk+utf8 version template /dz game website template
ICML 2022: UFRGS |作为最优策略转移基础的乐观线性支持和后继特征
Course strategy sharing plan of Zhejiang University
Online JSON to plaintext tool
Structure de stockage des graphiques