Find Documents with mongo-driver/mongo Using Expression for Value in Key/Value Pairs

Issue

I am using https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo and can’t seem to figure out how to insert an expression for the "value" of one of the key/value pairs when finding documents. My code is as follows:

cursor, err := collection.Find(context.TODO(), bson.D{{"date", "$gte: new Date((new Date().getTime() - (1000*60*60*24*100)))"}, {"enabled", true}})

What I am trying to achieve is to retrieve documents that are only a certain number of days old with respect to the current date. The query doesn’t fail but returns 0 documents. The value for date is an expression but if I don’t surround it with double quotes, Go doesn’t treat it as a key/value pair.

Any help would be greatly appreciated. Thanks.

Solution

You are providing a string value to the date field in the filter. As mentioned in the documentation, the syntax is:

filter := bson.D{{"<field>", bson.D{{"<operator>", "<value>"}}}}

Try refactoring the code as shown below:

import (
    "context" 
    "go.mongodb.org/mongo-driver/bson" 
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options" 
    "time"
)


cursor, err := collection.Find(context.TODO(), bson.D{
    {"date", bson.D{
        {"$gte", time.Now().AddDate(0, 0, -100)},
    }},
    { "enabled", true },
})

Answered By – Dharmaraj

Answer Checked By – Senaida (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.