首页 >后端开发 >Golang >如何使用 Go 驱动程序在 MongoDB 中创建嵌套 OR/AND 查询过滤器?

如何使用 Go 驱动程序在 MongoDB 中创建嵌套 OR/AND 查询过滤器?

Barbara Streisand
Barbara Streisand原创
2024-11-26 22:15:11467浏览

How to Create Nested OR/AND Query Filters in MongoDB with the Go Driver?

Go 中的 MongoDB 嵌套 OR/AND 查询过滤器

MongoDB Go 驱动程序允许您使用 $or 和 $ 创建复杂的查询过滤器和运营商。但是,如果您需要在这些顶级运算符中创建嵌套运算符,则由于驱动程序使用 bson.D 和 bson.E 元素,该过程可能会有点混乱。

以下示例演示了如何创建嵌套 OR/AND 查询过滤器:

package main

import (
    "context"
    "fmt"
    "time"

    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
)

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
    defer cancel()

    client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://localhost:27017"))
    if err != nil {
        panic(err)
    }
    defer client.Disconnect(ctx)

    collection := client.Database("test").Collection("people")

    // Create a nested OR/AND query filter
    filter := bson.D{
        {
            "$and", bson.A{
                bson.D{{"age", 30}},
                bson.D{{"$or", bson.A{
                    bson.D{{"name", "John"}},
                    bson.D{{"name", "Jane"}},
                }}},
            },
        },
    }

    // Find all people matching the filter
    cur, err := collection.Find(ctx, filter)
    if err != nil {
        panic(err)
    }
    defer cur.Close(ctx)

    // Iterate through the results and print each person's name
    for cur.Next(ctx) {
        var result bson.M
        if err := cur.Decode(&result); err != nil {
            panic(err)
        }
        fmt.Println(result["name"])
    }

    if err := cur.Err(); err != nil {
        panic(err)
    }
}

在此示例中:

  • 顶级 $and运算符由 bson.D 切片表示。
  • $and 运算符中的 $or 运算符也由 bson.D 切片表示。
  • $or 运算符中的每个条件都表示由 bson.D 元素组成。

需要注意的是,$and 运算符是默认的,因此您不必显式指定它。但是,如果您想在 $and 中嵌套其他运算符,则需要使用 bson.A 切片来表示条件数组。

以上是如何使用 Go 驱动程序在 MongoDB 中创建嵌套 OR/AND 查询过滤器?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn