Querying MongoDB Date Ranges Using Go and Mgo
When working with MongoDB collections that store dates, it's essential to understand how to query data within specified date ranges. This article addresses a query issue encountered when using Golang and Mgo.
The sample MongoDB collection named "my_sales" has documents with fields including "product_name," "price," and "sale_date," represented as ISODates. The objective is to retrieve sales records that fall within a specific date range.
In the MongoDB shell, the query looks like this:
However, when attempting to perform the same query in Golang using the Mgo driver, the following code returns no results:
The issue lies in the way Mgo handles BSON dates. For Go structs, time.Time should be used for date fields. Thus, the Sale struct should be defined as follows:
With this updated struct, the correct query in Golang is:
The above is the detailed content of How to Query MongoDB Date Ranges Using Go and Mgo?. For more information, please follow other related articles on the PHP Chinese website!