当前位置:网站首页>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)
}
边栏推荐
- First principles (optimal solution theory)
- seata
- How to set the enterprise wechat group robots to send messages regularly?
- 零基础自学SQL课程 | SQL基本函数大全
- 系统学习+主动探索,是最舒适的入门学习方式!
- Vivado FFT IP的使用说明
- 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)
- pytorch实现kaggle猫狗识别
- Detect objects and transfer images through mqtt
- Google Earth Engine(GEE) 03-矢量数据类型
猜你喜欢
随机推荐
One step forward is excellent, one step backward is ignorant
【微服务|Sentinel】sentinel数据持久化
C language character pointer and string initialization
UESTC (shenhengtao team) & JD AI (Mei Tao team) proposed a structured dual stream attention network for video Q & A, with performance SOTA! Better than the method based on dual video representation!
【AI应用】NVIDIA GeForce RTX 3060的详情参数
The latest cloud development wechat balance charger special effect applet source code
[从零开始学习FPGA编程-48]:视野篇 - 智能传感器的发展与应用
[try to hack] kill evaluation
pytorch实现kaggle猫狗识别
seata
用pytorch进行CIFAR-10数据集分类
Discuz小鱼游戏风影传说商业GBK+UTF8版模板/DZ游戏网站模板
Structure de stockage des graphiques
【AI应用】NVIDIA Tesla V100S-PCIE-32GB的详情参数
Stream + Nacos
如何设置企业微信群机器人定时发消息?
Discuz淘宝客网站模板/迪恩淘宝客购物风格商业版模板
MySQL删除表后如何使ID从1开始
Started a natural language model bloom
pytorch 入门指南



![[sword finger offer] 47 Maximum value of gifts](/img/bc/1aff1223b1672c4089151dc56c4d4e.png)





