How can I query MongoDB with date range using mgo and Go?

后端 未结 3 1944
花落未央
花落未央 2020-12-10 02:15

Hi I have a collection named \"my_sales\" having fields product_name, price, sale_date.

My doc looks like

{
    \"_id\" : ObjectId(\"5458b6ee09d76eb7         


        
相关标签:
3条回答
  • 2020-12-10 02:46

    You Can also check this out. If you are using this method then use parse:

    db.getCollection('user').find({
        createdOn: {
            $gt: ISODate("2020-01-01T00:00:00.000Z"),
            $lt: ISODate("2020-03-01T00:00:00.000Z")
        }
    })
    

    Function without parsing: Get values using string

    db, err := GetDB()
    if err != nil {
        return nil, err
    }
    defer db.Session.Close()
    
    var date []models.User
    
    coll := db.C(constants.USERTABLE)
    
    findQuery := bson.M{"createdOn": bson.M{"$gt": echo.FromDate, "$lt": echo.ToDate}}
    
    shared.BsonToJSONPrint(findQuery)
    
    err = coll.Find(findQuery).All(&date)
    if err != nil {
        return nil, err
    }
    return date, nil
    }
    
    0 讨论(0)
  • 2020-12-10 02:52

    mgo supports time.Time for BSON dates.

    So if your struct looks like this:

    type Sale struct {
        ProductName string    `bson:"product_name"`
        Price       int       `bson:"price"`
        SaleDate    time.Time `bson:"sale_date"`
    }
    

    Then you can query it like this:

    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)
    
    0 讨论(0)
  • 2020-12-10 03:03

    I have new way to query date range:

    // convert to date
    fromTime := time.Unix(1509358405981/1000, 0)     
    
    // Convert date to ObjectID with time    
    fromObjectBson := bson.NewObjectIdWithTime(fromTime)
    
    // condition     
    bson.M{"_id":bson.M{"$gt": fromObjectBson}} 
    

    This will speedup your query.

    0 讨论(0)
提交回复
热议问题