简体   繁体   English

如何使用 mgo 和 Go 查询具有日期范围的 MongoDB?

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

Hi I have a collection named "my_sales" having fields product_name, price, sale_date.嗨,我有一个名为“my_sales”的集合,其中包含 product_name、price、sale_date 字段。

My doc looks like我的文档看起来像

{
    "_id" : ObjectId("5458b6ee09d76eb7326df3a4"),
    "product_name" : product1,
    "price" : 200,
    "sale_date" : ISODate("2014-11-04T11:22:19.589Z")
}
{
    "_id" : ObjectId("5458b6ee09d76eb7326df3a4"),
    "product_name" : product1,
    "price" : 200,
    "sale_date" : ISODate("2014-11-04T11:22:19.589Z")
}
{
    "_id" : ObjectId("5458b6ee09d76eb7326df3a4"),
    "product_name" : product1,
    "price" : 200,
    "sale_date" : ISODate("2014-11-04T11:22:19.589Z")
}
{
    "_id" : ObjectId("5458b6ee09d76eb7326df3a4"),
    "product_name" : product1,
    "price" : 200,
    "sale_date" : ISODate("2014-11-05T11:22:19.589Z")
}

I tried in mongo shell like this我在这样的 mongo shell 中尝试过

 db.my_sales.find({ sale_date: { $gt: ISODate("2014-11-04"), $lt: new ISODate("2014-11-05") });

It giving the correct result.它给出了正确的结果。 Now I need to query same thing using golang I tried like this现在我需要使用 golang 查询相同的东西,我试过这样

 var sales_his []Sale
 err := c.Find(bson.M{"sale_date":bson.M{ "$gt": "ISODate("+date_from+")", "$lt": "ISODate("+date_to+")" }    }).All(&sales_his)

Its giving null result please help它给出空结果请帮忙

mgo supports time.Time for BSON dates.氧化镁支持了time.time为BSON日期。

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)

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.这将加速您的查询。

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM