How to Query a MongoDB Collection with a Date Range Using Mgo and Go?

Patricia Arquette
Release: 2024-11-08 01:57:02
Original
838 people have browsed it

How to Query a MongoDB Collection with a Date Range Using Mgo and Go?

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!