使用golang mgo查询mongodb日期范围内的数据

3

我尝试按照这里提到的解决方案 How can I query MongoDB with date range using mgo and Go? 进行操作,但是我似乎无法获得关于dob范围的结果。在mongodb中,“dob”被存储为:

"dob": {
    "$date": "1967-06-28T00:00:00.000Z"
}

没有dob查询时它可以正常工作。我尝试了切换$lt和$gt,但仍然没有运气。有人知道如何让它工作吗?我已经打印出dobLower和dobUpper,它们似乎都是有效的日期,比如2000-06-28 21:57:06.666025643 +0000 UTC。dob的模型是Dob time.Timejson:"dob" bson:"dob"
ageLower, err := strconv.Atoi(filters["ageLower"])
ageUpper, err := strconv.Atoi(filters["ageUpper"])
heightLower, err := strconv.Atoi(filters["heightLower"])
heightUpper, err := strconv.Atoi(filters["heightUpper"])
if err != nil {
    return nil, err
}

dobUpper := time.Now().AddDate(-ageLower, 0, 0)
dobLower := time.Now().AddDate(-ageUpper, 0, 0)

pColl := s.DB("mydb").C("profiles")

query := bson.M{
    "$and": []bson.M{
        bson.M{"active": bson.M{"$eq": true}},
        bson.M{"gender": bson.M{"$ne": u.Gender}},
        bson.M{"_id": bson.M{"$nin": u.HiddenProfiles}},
        bson.M{"_id": bson.M{"$ne": u.ProfileID}},
        bson.M{"dob": bson.M{"$gt": dobLower , "$lt": dobUpper}},
        bson.M{"height": bson.M{"$gt": heightLower, "$lt": heightUpper}},
    },
}

return pColl.Find(query).Select(bson.M{"first_name": 0}).All(&profiles)

希望能得到帮助,非常感谢。


这可能会有帮助。日期范围搜索 - Muhammad Tariq
2个回答

3

另一个解决方案是将字符串转换为ISODate格式。

collection := client.Database("Hello").Collection("demo")
    eventStartTime := "2013-10-01T01:11:18.965Z" //string format
    eventEndTime := "2014-12-03T01:11:18.965Z"   //string format

    const (
        layoutISO = "2006-01-02T15:04:05.000Z"
    )

    //import "time" package.
    t1, _ := time.Parse(layoutISO, eventStartTime) //converted to ISODate format
    t2, _ := time.Parse(layoutISO, eventEndTime)   //converted to ISODate format
    //fmt.Println(t1)
    filterCursor, err := collection.Find(context.TODO(), bson.M{"sentat": bson.M{"$gt": t1, "$lt": t2}})
    if err != nil {
        log.Fatal(err)
    }
    var result []bson.M
    if err = filterCursor.All(context.TODO(), &result); err != nil {
        log.Fatal(err)
    }
    fmt.Println(result)

我希望能对你有所帮助。

1
如果您将日期存储为int64,则可以使用$lt等与整数比较一起使用,但首先您需要添加一个日期字段作为int64。为此,请对集合进行迭代,并使用时间将日期从字符串转换为int64,方法是创建一个时间,然后获取其秒数。添加新日期时也将其保存为int64。整数比较将更快,如果对其进行索引,则索引将比文本索引小。
iter := pColl.Find(nil).Iter()
for iter.Next(&profile){
    t, _ := time.Parse(time.RFC3339, profile.DOB)
    x := t.Unix()
    theUpdate := bson.M{"$set": bson.M{"dobint": x}}
    pColl.UpdateId(profile.ID, theUpdate)
}
iter.Close()

1
我一直面临着同样的问题。这似乎可以解决它。但是,我必须更改Mongo中的每个记录。还有其他解决方案吗? - sairohith
@sairohith 看看我的解决方案,希望能帮到你。 - infiniteLearner

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接