当前位置:网站首页>Golang uses Mongo driver operation -- Query (array related)
Golang uses Mongo driver operation -- Query (array related)
2022-06-27 23:43:00 【lsjweiyi】
The array lookup is slightly different , The space for , Write separately .
Need to be exactly the same to match , Include the order of elements . And the demonstration output is converted into string form :
// The most basic query array related data , Match of the following array , Need to be exactly the same to match , Include the order of elements
// Reference resources :https://www.mongodb.com/docs/manual/tutorial/query-arrays/
func Array(mongo *mongo.Database, ctx context.Context) {
stringlist := []string{
"test1", "test2", "test3"}
findFilter := bson.M{
"stringlist": stringlist}
result := mongo.Collection("test").FindOne(ctx, findFilter)
// Turn it into string Output
rawByte, _ := result.DecodeBytes()
fmt.Println(rawByte.String())
}
use all Keyword implementation : The query array contains the following elements , And order independent queries . When traversing the result, it can be converted to include only values and not key Array of :
func ArrayAll(mongo *mongo.Database, ctx context.Context) {
stringlist := []string{
"test3", "test2"}
findFilter := bson.M{
"stringlist": bson.M{
"$all": stringlist}}
result := mongo.Collection("test").FindOne(ctx, findFilter)
// Convert the values of the document's fields into an array , Then output one by one , This method contains only values , Without a key
rawByte, _ := result.DecodeBytes()
rawV, _ := rawByte.Values()
for i := 0; i < len(rawV); i++ {
fmt.Println("rawV:", rawV[i])
}
}
The field of array type corresponds to a value , Indicates whether the element is included in the query array . When traversing the result, it is converted into an array of key value pairs :
// The field of array type corresponds to a value , Indicates whether the element is included in the query array
func ArrayAtLeastOne(mongo *mongo.Database, ctx context.Context) {
// You can also use gte Wait for keywords to match whether there are elements greater than or less than a certain value
findFilter := bson.M{
"stringlist": "test3"}
result := mongo.Collection("test").FindOne(ctx, findFilter)
// Convert document fields into arrays , Then output one by one , This is in the form of key value pairs
rawByte, _ := result.DecodeBytes()
rawV, _ := rawByte.Elements()
for i := 0; i < len(rawV); i++ {
fmt.Println("rawV:", rawV[i])
}
}
The query of multiple conditions is different from our normal understanding , The result can also be obtained by array subscript :
// Query when there are multiple conditions
func ArrayGtAndLt(mongo *mongo.Database, ctx context.Context) {
// These two conditions , It doesn't have to work on the same element , As long as there is an element greater than 20, And some element is less than 10, So the following statement can find multiple records
findFilter := bson.M{
"intlist": bson.M{
"$gt": 20, "$lt": 10}}
cur, err := mongo.Collection("test").Find(ctx, findFilter)
if err != nil {
fmt.Println("err")
}
// Traversal data
for cur.TryNext(ctx) {
// This method is converted into an array , Use array subscript to get data , The output is in the form of key value pairs
result := cur.Current.Index(0)
fmt.Println(result)
}
cur.Close(ctx)
}
The following multi condition query is similar to our normal understanding . The result can also be key DE value :
// Contrary to the above method , There must be an element that satisfies all the conditions at the same time , It's a successful query
func ArrayElemMatch(mongo *mongo.Database, ctx context.Context) {
// You need an element that satisfies both conditions , No element can satisfy more than 20 Less than 10, So the query will fail
findFilter := bson.M{
"intlist": bson.M{
"$elemMatch": bson.M{
"$gt": 20, "$lt": 10}}}
cur, err := mongo.Collection("test").Find(ctx, findFilter)
if err != nil {
fmt.Println("err")
}
// Traversal data
for cur.TryNext(ctx) {
// This method is converted into an array , use key Value to get data , Output the corresponding value
result := cur.Current.Lookup("intlist")
fmt.Println(result)
}
cur.Close(ctx)
}
Query by array length , The result can also be Lookup Take the key value of the nested document
// Query by array length
func ArraySize(mongo *mongo.Database, ctx context.Context) {
// You need an element that satisfies both conditions , No element can satisfy more than 20 Less than 10, So the query will fail
findFilter := bson.M{
"intlist": bson.M{
"$size": 11}}
cur, err := mongo.Collection("test").Find(ctx, findFilter)
if err != nil {
fmt.Println("err")
}
// Traversal data
for cur.TryNext(ctx) {
// There can be more than one key, these key It is hierarchical , Get the key first object Value , Then look for the key from the value id Value , It is very convenient for us to obtain deeply nested data
result := cur.Current.Lookup("object", "id")
fmt.Println(result)
}
cur.Close(ctx)
}
Query arrays that do not contain elements :
// The query does not include 0 and 7 Array of , Particular attention , If there is no... In the document intlist Field , It also meets the conditions
findFilter := bson.M{
"intlist": bson.M{
"$nin": bson.A{
0, 7}}}
// The query of array can also use dot and subscript , Such as .0: The comparison subscript is 0 Whether the element of the satisfies the condition :
// Query the first... Of the array 1 Whether the elements are greater than 5
findFilter := bson.M{
"intlist.0": bson.M{
"$gt": 5}}
Specifies that only the... Of the array is queried N Elements :
func ArrayElement(mongo *mongo.Database, ctx context.Context) {
filter := bson.M{
} // Empty structure matches all
// use slice Key assignment query No N Elements ,-1 Represents the last element of the query
options := options.FindOptions{
Projection: bson.M{
"intlist": bson.M{
"$slice": -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("intlist")
fmt.Println(result)
}
cur.Close(ctx)
}
边栏推荐
- Stream + Nacos
- 超纲练习题不超纲
- NDSS 2022 接收的列表
- Download versions such as typora 1.2.5
- 【PCL自学:Segmentation3】基于PCL的点云分割:区域增长分割
- 零基础自学SQL课程 | IF函数
- Online JSON to plaintext tool
- Detailed explanation of MATLAB axis coordinate axis related settings
- Golang - the difference between new and make
- Can you do these five steps of single cell data cleaning?
猜你喜欢

Introduction to quantitative trading

零基础自学SQL课程 | SQL中的日期函数大全

ASP.NET仓库进销存ERP管理系统源码 ERP小程序源码

Stream + Nacos

Discuz淘宝客网站模板/迪恩淘宝客购物风格商业版模板

Excel print settings public header

电子科大(申恒涛团队)&京东AI(梅涛团队)提出用于视频问答的结构化双流注意网络,性能SOTA!优于基于双视频表示的方法!

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

手把手教你移植 tinyriscv 到FPGA上

【蓝桥杯集训100题】scratch数字计算 蓝桥杯scratch比赛专项预测编程题 集训模拟练习题第16题
随机推荐
c语言之字符串数组
mysql读写分离配置
往前一步是优秀,退后一步是懵懂
居家办公竟比去公司上班还累?
vmware虚拟机桥接连通
Small chip chiplet Technology
Stream + Nacos
抓出那些重复的基因
Discuz小鱼游戏风影传说商业GBK+UTF8版模板/DZ游戏网站模板
Use of go log package log
Windows环境下的ELK——Logstash+Mysql(4)
[sword finger offer] 47 Maximum value of gifts
小程序referer
c语言-日期格式化[通俗易懂]
Detailed explanation of MATLAB axis coordinate axis related settings
【PCL自学:Segmentation3】基于PCL的点云分割:区域增长分割
【微服务|Sentinel】sentinel数据持久化
One step forward is excellent, one step backward is ignorant
go日志包 log的使用
使用cef3开发的浏览器不支持flash问题的解决