Querying MongoDB with Date Range Using Mgo and Go
You've encountered a challenge while querying a MongoDB collection with a date range using the Mgo library in Go. Your query is not returning the expected results, despite working correctly in the MongoDB shell.
To resolve this issue, consider the following solution:
Handling Date/Time Values in Go
Mgo supports time.Time for handling BSON dates. In your Go struct, define the SaleDate field as follows:
<code class="go">type Sale struct { ProductName string `bson:"product_name"` Price int `bson:"price"` SaleDate time.Time `bson:"sale_date"` }</code>
Constructing the Query
Once your struct is defined, you can construct the query using bson.M:
<code class="go">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) var sales_his []Sale err = c.Find( bson.M{ "sale_date": bson.M{ "$gt": fromDate, "$lt": toDate, }, }).All(&sales_his)</code>
In this query, we're using $gt and $lt operators to specify the date range. The fromDate and toDate variables are of type time.Time.
By implementing these changes, you should be able to successfully query your MongoDB collection with a date range using Mgo and Go.
The above is the detailed content of How to Query a MongoDB Collection with a Date Range Using Mgo and Go?. For more information, please follow other related articles on the PHP Chinese website!