This chapter introduces the usage of Golang MongoDB document queries.
Prerequisite Tutorials
Tip: If you are unfamiliar with MongoDB query syntax, please read the MongoDB tutorial first. The expression syntax used for MongoDB operations in Golang is the same.
Prepare Test Data
Insert a batch of document data into the coll
collection.
docs := []interface{}{
bson.D{
{"item", "journal"},
{"qty", 25},
{"size", bson.D{
{"h", 14},
{"w", 21},
{"uom", "cm"},
}},
{"status", "A"},
},
// ... (other document data)
}
result, err := coll.InsertMany(context.Background(), docs)
Query All Documents
cursor, err := coll.Find(
context.Background(),
bson.D{}, // Set empty query condition
)
Equality Query Conditions
Similar to SQL’s equality match.
cursor, err := coll.Find(
context.Background(),
bson.D{{"status", "D"}}, // Equivalent condition: status = D
)
in
Query Operator
Similar to SQL’s in
query.
cursor, err := coll.Find(
context.Background(),
bson.D{{"status", bson.D{{"$in", bson.A{"A", "D"}}}}}) // Equivalent condition: status in ('A', 'D')
and
Query Conditions
Similar to SQL’s and
logical expression.
cursor, err := coll.Find(
context.Background(),
bson.D{ // Equivalent condition: status='A' and qty < 30
{"status", "A"},
{"qty", bson.D{{"$lt", 30}}},
})
or
Query Conditions
Similar to SQL’s or
logical expression.
cursor, err := coll.Find(
context.Background(),
bson.D{ // Equivalent condition: status = "A" OR qty < 30
{"$or", // Using $or operator
bson.A{ // Using bson.A array type definition
bson.D{{"status", "A"}},
bson.D{{"qty", bson.D{{"$lt", 30}}}},
}},
})
Compound Query Example
cursor, err := coll.Find(
context.Background(),
bson.D{ // Equivalent condition: status = "A" AND ( qty < 30 OR item LIKE "p%")
{"status", "A"},
{"$or", bson.A{
bson.D{{"qty", bson.D{{"$lt", 30}}}},
bson.D{{"item", primitive.Regex{Pattern: "^p", Options: ""}}},
}},
})
Traverse Query Results
Example 1
// Query documents where name is 'Bob'
cursor, err := coll.Find(context.TODO(), bson.D{{"name", "Bob"}}, opts)
if err != nil {
log.Fatal(err)
}
// Define an array of documents of type bson.M, where bson.M is a key-value data structure similar to a map
var results []bson.M
// Use the All function to retrieve all query results and save the results to the results variable.
if err = cursor.All(context.TODO(), &results); err != nil {
log.Fatal(err)
}
// Traverse the results array
for _, result := range results {
fmt.Println(result)
}
Explanation: The example uses the bson.M type to store document data. You can customize a struct type as long as the fields match the document.
Example 2:
// Define a variable of type struct to save the query result
var result struct {
Value float64
}
// Define the document query condition name = 'pi'
filter := bson.D{{"name", "pi"}}
// Create a context object and set the query timeout to 5 seconds
ctx, cancel = context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
// Query a single data based on the condition, and use the Decode function to save the result to the result variable
err = collection.FindOne(ctx, filter).Decode(&result)
// Check for query errors
if err == mongo.ErrNoDocuments {
// Document not found
fmt.Println("Document does not exist")
} else if err != nil {
log.Fatal(err)
}
// Other handling
Tip: For more sophisticated MongoDB query expression syntax, please refer to the MongoDB tutorial.