当前位置:网站首页>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)
}
边栏推荐
- 企业架构师面试的100个问题
- Halcon's region: features of multiple regions (6)
- The latest cloud development wechat balance charger special effect applet source code
- 通过中金证券经理的开户二维码开股票账户安全吗?还是去证券公司开户安全?
- webserver流程图——搞懂webserver各模块间调用关系
- Swing UI——容器(一)
- What if Fiddler fails to listen to the interface
- 捷码赋能案例:湖南天辰产研实力迅速提升!实战玩转智慧楼宇/工地等项目
- MSP430F5529 单片机 读取 GY-906 红外温度传感器
- 如何设置企业微信群机器人定时发消息?
猜你喜欢
2022年PMP项目管理考试敏捷知识点(3)
To build a "strong core" in Nansha, the first IC Nansha conference was held in Nansha
Cornernet由浅入深理解
思源笔记订阅停止直接删云端数据嘛?
【PCL自学:Segmentation3】基于PCL的点云分割:区域增长分割
[Blue Bridge Cup training 100 questions] scratch digital calculation Blue Bridge Cup competition special prediction programming question collective training simulation exercise question No. 16
seata
The latest cloud development wechat balance charger special effect applet source code
clickonce 部署ClickOnce应用程序时出错-清单中的引用与下载的程序集的标识不匹配
在线JSON转PlainText工具
随机推荐
文献综述如何挑选文献进行阅读,比如我的检索结果有200多篇根本看不完,如何进行文献挑选呢?...
Golang - the difference between new and make
Stream + Nacos
Practice torch FX: pytorch based model optimization quantization artifact
Swing UI container (I)
The latest cloud development wechat balance charger special effect applet source code
Prediction of benign / malignant breast tumors (logistic regression classifier)
Working at home is more tiring than going to work at the company?
手把手教你移植 tinyriscv 到FPGA上
沉寂了一段时间 ,我又出来啦~
零基础自学SQL课程 | IF函数
【tinyriscv verilator】分支移植到正点原子达芬奇开发板
Sentinel
上手了一个自然语言模型BLOOM
用pytorch进行CIFAR-10数据集分类
撰写外文时怎样引用中文文献?
MySQL删除表后如何使ID从1开始
图的存储结构
Cornernet understands from simple to profound
vmware虚拟机桥接连通