skip to Main Content

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


  1. Add some error handling, this may help you figure out why. e.g:

    cursor, err := collection.Find(context.Background(), bson.M{"endDate": bson.M{"$gt": primitive.NewDateTimeFromTime(date)}})
    if err != nil {
        log.Fatal(err)
    }
    defer cursor.Close(context.Background())
    
    for cursor.Next(context.Background()) {
        var result bson.M
        if err := cursor.Decode(&result); err != nil {
            log.Fatal(err)
        }
    
        // Process the document (result) here
    }
    
    if err := cursor.Err(); err != nil {
        log.Fatal(err)
    }
    
    Login or Signup to reply.
  2. The mongo driver handles time.Time values as expected, simply use / pass that:

    cursor, err := collection.Find(context.Background(), bson.M{"endDate": bson.M{"$gt": date}})
    

    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 of date), or the endDate property in MongoDB is not of date type.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search