Querying MongoDB with Date Range Using mgo and Go
MongoDB's powerful query capabilities allow for precise filtering of data based on specific criteria, including date ranges. Using mgo, a popular Go library for MongoDB, querying within date ranges is straightforward.
Consider the following MongoDB document:
{ "_id" : ObjectId("5458b6ee09d76eb7326df3a4"), "product_name" : "product1", "price" : 200, "sale_date" : ISODate("2014-11-04T11:22:19.589Z") }
To query this document for documents sold within a specific date range, the following steps can be taken:
Create a Go Struct for Sales Data:
<code class="go">type Sale struct { ProductName string `bson:"product_name"` Price int `bson:"price"` SaleDate time.Time `bson:"sale_date"` }</code>
Parse Date Ranges from Strings:
<code class="go">fromDate, err := time.Parse(timeLayout, dateFrom) if err != nil { return err } toDate, err := time.Parse(timeLayout, dateTo) if err != nil { return err }</code>
Query with Date Range:
<code class="go">var sales []Sale err = c.Find( bson.M{ "sale_date": bson.M{ "$gt": fromDate, "$lt": toDate, }, }, ).All(&sales)</code>
By utilizing the $gt and $lt MongoDB operators, the query selects documents where the sale_date field exceeds fromDate and falls short of toDate, effectively filtering sales within the specified date range.
The above is the detailed content of How do you Query MongoDB with Date Range using mgo and Go?. For more information, please follow other related articles on the PHP Chinese website!