I am attempting to query my database using Go’s mongodb driver to retrieve all documents where the endDate is greater than a date passed in as type time.Time. I am getting 0 documents returned with my query.
Here are a few of my documents (endDate type in mongodb: Date):
_id: ObjectId('6466db9f4795a05298cf860d')
frequency: 1
startDate: 2023-05-18T22:14:14.000+00:00
endDate: 2023-09-30T20:00:00.000+00:00
cost: 12.99
paid: ["2023-04", "2023-05"]
_id: ObjectId('6466e279f708fad7ec8363ae')
frequency: 1
startDate: 2023-05-18T22:44:00.000+00:00
endDate: 2023-11-30T19:00:00.000+00:00
cost: 45.66
paid: ["2023-05"]
Here is the query (date is of type time.Time and the value is 2023-05-01 00:00:00 +0000 UTC):
cursor, err := collection.Find(context.Background(), bson.M{"endDate": bson.M{"$gt": primitive.NewDateTimeFromTime(date)}})
Not sure what I am doing wrong. Any help would be appreciated. Thanks!
2
Answers
Add some error handling, this may help you figure out why. e.g:
The mongo driver handles
time.Time
values as expected, simply use / pass that:If this still doesn’t return any documents, then
collection
likely designates a wrong collection (possibly in the wrong database), or you really don’t have matching documents (check the value ofdate
), or theendDate
property in MongoDB is not of date type.