Home > Article > Backend Development > How to Create Nested OR/AND Query Filters in MongoDB with the Go Driver?
MongoDB Nested OR/AND Query Filter in Go
The MongoDB Go driver allows you to create complex query filters using the $or and $and operators. However, if you need to create nested operators within these top-level operators, the process can be a bit confusing due to the driver's use of bson.D and bson.E elements.
The following example demonstrates how to create a nested OR/AND query filter:
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) } }
In this example:
It's important to note that the $and operator is the default, so you don't have to explicitly specify it. However, if you want to nest other operators within $and, you'll need to use a bson.A slice to represent the array of conditions.
The above is the detailed content of How to Create Nested OR/AND Query Filters in MongoDB with the Go Driver?. For more information, please follow other related articles on the PHP Chinese website!