Querying MongoDB Date Range in Go with mgo
When working with MongoDB, querying documents based on date ranges is a common operation. This article addresses how to perform such queries using mgo, a MongoDB driver for Go.
Problem:
You have a MongoDB collection named "my_sales" with fields for product name, price, and sale date. You need to retrieve all sales records within a specific date range using Go and mgo.
Solution:
mgo supports querying dates using the time.Time type. Therefore, for the given example with the following document structure:
<code class="go">type Sale struct { ProductName string `bson:"product_name"` Price int `bson:"price"` SaleDate time.Time `bson:"sale_date"` }</code>
To query sales within the specified date range, you can use the following code:
<code class="go">package main import ( "context" "fmt" "log" "time" "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" ) func main() { // Connect to MongoDB session, err := mgo.Dial("localhost:27017") if err != nil { log.Fatal(err) } defer session.Close() // Get a collection c := session.DB("my_db").C("my_sales") // Define the date range fromDate := time.Date(2014, time.November, 4, 0, 0, 0, 0, time.UTC) toDate := time.Date(2014, time.November, 5, 0, 0, 0, 0, time.UTC) // Query the collection results := []Sale{} err = c.Find( bson.M{ "sale_date": bson.M{ "$gt": fromDate, "$lt": toDate, }, }).All(&results) if err != nil { log.Fatal(err) } // Print the results for _, sale := range results { fmt.Println(sale) } }</code>
By providing the bson.M map with the appropriate date range criteria, you can retrieve all sales that occurred between the specified dates.
The above is the detailed content of How to Query MongoDB Date Range in Go with mgo?. For more information, please follow other related articles on the PHP Chinese website!