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 运算符是默认的,因此您不必显式指定它。但是,如果您想在 $and 中嵌套其他运算符,则需要使用 bson.A 切片来表示条件数组。
以上是如何使用 Go 驱动程序在 MongoDB 中创建嵌套 OR/AND 查询过滤器?的详细内容。更多信息请关注PHP中文网其他相关文章!