当前位置:网站首页>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)
}
边栏推荐
- 零基础自学SQL课程 | IF函数
- VMware virtual machine bridging connectivity
- Started a natural language model bloom
- Summary of solutions to cross system data consistency problems
- 【AI应用】NVIDIA Tesla V100S-PCIE-32GB的详情参数
- mysql读写分离配置
- How to set the enterprise wechat group robots to send messages regularly?
- Discuz淘宝客网站模板/迪恩淘宝客购物风格商业版模板
- 【tinyriscv verilator】分支移植到正点原子达芬奇开发板
- 第一性原理(最优解理论)
猜你喜欢

Feign通过自定义注解实现路径的转义

vivado 如何添加时序约束

First principles (optimal solution theory)

Cornernet由浅入深理解

c语言字符指针、字符串初始化问题

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

c语言之字符串数组

Halcon's region: features of multiple regions (6)

Teach you how to transplant tinyriscv to FPGA

Prediction of benign / malignant breast tumors (logistic regression classifier)
随机推荐
[sword finger offer] 47 Maximum value of gifts
[Blue Bridge Cup training 100 questions] scratch digital calculation Blue Bridge Cup competition special prediction programming question collective training simulation exercise question No. 16
沉寂了一段时间 ,我又出来啦~
mysql读写分离配置
ICML 2022: UFRGS |作为最优策略转移基础的乐观线性支持和后继特征
const关键字及其作用(用法),C语言const详解
Swing UI container (I)
vivado 如何添加时序约束
良/恶性乳腺肿瘤预测(逻辑回归分类器)
跨系统数据一致性问题解决方案汇总
Realization of kaggle cat dog recognition by pytorch
C# Winform 读取Resources图片
零基础自学SQL课程 | IF函数
ICML 2022:ufrgs | optimistic linear support and subsequent features as the basis for optimal strategy transfer
Classification of cifar-10 dataset with pytorch
How to use the apipost script - global variables
Discuz small fish game wind shadow legend business gbk+utf8 version template /dz game website template
Excel print settings public header
第 2 章 集成 MP
【剑指Offer】47. 礼物的最大价值