如何使用Go语言结构化BSON查询,包括查询、条件和in操作?

huangapple go评论78阅读模式
英文:

How to use structure a bson query with query,where and in using go

问题

我想根据时间范围和在$in中使用的字段来获取文档条目。我可以很容易地使用mongoose和nodejs来实现,如下所示,其中param是键,params是一个数组:

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

以下是我使用go和bson的尝试,我发现很难构建查询:

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

请问有人可以帮助我解决这个问题吗?

英文:

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

答案1

得分: 0

你的尝试不是一个有效的MongoDB查询。请尝试使用以下代码替代:

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

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},
    }

huangapple
  • 本文由 发表于 2021年10月10日 01:24:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/69509057.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定