我的 mongoDB 上的日期和我的结构中映射的日期具有类似“02/10/2018 11:55:20”的值。
您可以采取多种方式。正如评论中提到的,第一个是将string
日期转换为实际的日期格式。另请参阅MongoDB 日期。建议以正确的日期格式存储日期值以提高性能。
如果您有文件:
{ "a": 1, "b": ISODate("2018-10-02T11:55:20Z") }
使用mongo-go-driver(当前 v1.2.x),您可以执行以下操作来查找和比较使用日期:
initDate, err := time.Parse("02/01/2006 15:04:05", "01/10/2018 11:55:20")
filter := bson.D{
{"b", bson.D{
{"$gt", initDate},
}},
}
cursor, err := collection.Find(context.Background(), filter)
请注意上面示例中的布局值time.Parse()
。它需要匹配字符串布局/格式。
另一种不转换值的方法是使用MongoDB Aggregation Pipeline。您可以使用$dateFromString运算符将string
日期转换为日期,然后使用$match阶段按日期过滤。
例如,给定文档:
{ "a": 1, "b": "02/10/2018 11:55:20" }
{ "a": 2, "b": "04/10/2018 10:37:19" }
你可以试试:
// Add a new field called 'newdate' to store the converted date value
addFieldsStage := bson.D{
{"$addFields", bson.D{
{"newdate", bson.D{
{"$dateFromString", bson.D{
{"dateString", "$b"},
{"format", "%d/%m/%Y %H:%M:%S"},
}},
}},
}},
}
initDate, err := time.Parse("02/01/2006 15:04:05", "02/10/2018 11:55:20")
// Filter the newly added field with the date
matchStage := bson.D{
{"$match", bson.D{
{"newdate", bson.D{
{"$gt", initDate},
}},
}},
}
pipeline := mongo.Pipeline{addFieldsStage, matchStage}
cursor, err := collection.Aggregate(context.Background(), pipeline)