使用golang mgo查询日期范围之间的mongodb日期
我试着遵循这里提到的解决方案,但似乎无法得到dob范围的结果。mongodb中的“dob”存储为:使用golang mgo查询日期范围之间的mongodb日期,mongodb,go,filtering,mgo,Mongodb,Go,Filtering,Mgo,我试着遵循这里提到的解决方案,但似乎无法得到dob范围的结果。mongodb中的“dob”存储为: "dob": { "$date": "1967-06-28T00:00:00.000Z" } 没有dob查询,它工作正常。我尝试过切换$lt和$gt,但仍然没有成功。有人知道如何让它工作吗?我已经打印出了dobLower和dobLower,它们似乎都是有效日期,比如2000-06-28 21:57:06.666025643+0000 UTC。dob的模型是 Dob time.timejs
"dob": {
"$date": "1967-06-28T00:00:00.000Z"
}
没有dob查询,它工作正常。我尝试过切换$lt和$gt,但仍然没有成功。有人知道如何让它工作吗?我已经打印出了dobLower
和dobLower
,它们似乎都是有效日期,比如2000-06-28 21:57:06.666025643+0000 UTC
。dob的模型是
Dob time.time
json:“Dob”bson:“Dob”
非常感谢您的帮助。谢谢。如果您将日期存储为int64,则可以使用$lt etc进行整数比较,但首先必须将日期字段添加为int64。要执行此操作,请在集合上迭代,并通过创建一个时间,然后从中获取秒数,使用time将日期从string转换为int64。添加新日期时,也将其另存为int64。Int比较会更快,如果你给它编制索引,索引会比文本索引小
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()
另一种解决方案是将字符串转换为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)
我希望它能帮助你。我一直面临着同样的问题。这似乎解决了问题。但是,我必须更改mongo的所有记录。还有其他解决方案吗?@sairohith请看我的解决方案一次,希望它能帮助你。这会很有帮助。
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)