Home > Software design >  How to use structure a bson query with query,where and in using go
How to use structure a bson query with query,where and in using go

Time:10-10

I would like to get document entries based on time range and a field that is used in $in. I can do it very easily using mongoose and nodejs like so where param is the key and params is an array

Data.find( 
         {
          timestamp:
                 {
          $gte: new Date(query.startDate),
          $lt: new Date(query.endDate)
               }
         }
       ).where(`${param}`).in(params);

Below is my attempt with bson using go and bson. I am finding it diffucult on how to structure the query

aliases := []string {"000","111"}
query := bson.M{
        "datetime": bson.M{
            "$gt": startDate,
            "$lt": endDate,
        },
     "$where":bson.M{"device_alias":bson.M{"$in": aliases}}
        
    }

Kindly could someone help me figure this out

CodePudding user response:

Your attempt is not a valid mongodb query. Try this instead:

query := bson.M{
        "datetime": bson.M{
            "$gt": startDate,
            "$lt": endDate,
        },
        "device_alias":bson.M{"$in": aliases},
    }
  • Related