Home > Article > Backend Development > How to Query MongoDB Date Ranges with Mgo and Go?
In MongoDB, documents can be queried based on date ranges. To achieve this in Go using mgo, the following steps can be taken:
For example, suppose a collection named "my_sales" has the following fields: "product_name," "price," and "sale_date." A corresponding Go struct can be defined as:
<code class="go">type Sale struct { ProductName string `bson:"product_name"` Price int `bson:"price"` SaleDate time.Time `bson:"sale_date"` }</code>
Once the struct is defined, you can proceed with the query using mgo. Consider the following example:
<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>
Here, the $gt (greater than) and $lt (less than) operators are used to specify the desired date range for the "sale_date" field. The result is stored in the sales_his slice.
The above is the detailed content of How to Query MongoDB Date Ranges with Mgo and Go?. For more information, please follow other related articles on the PHP Chinese website!