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

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

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

问题

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

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

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

  1. aliases := []string{"000", "111"}
  2. query := bson.M{
  3. "datetime": bson.M{
  4. "$gt": startDate,
  5. "$lt": endDate,
  6. },
  7. "$where": bson.M{"device_alias": bson.M{"$in": aliases}},
  8. }

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

英文:

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

  1. Data.find(
  2. {
  3. timestamp:
  4. {
  5. $gte: new Date(query.startDate),
  6. $lt: new Date(query.endDate)
  7. }
  8. }
  9. ).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

  1. aliases := []string {"000","111"}
  2. query := bson.M{
  3. "datetime": bson.M{
  4. "$gt": startDate,
  5. "$lt": endDate,
  6. },
  7. "$where":bson.M{"device_alias":bson.M{"$in": aliases}}
  8. }

Kindly could someone help me figure this out

答案1

得分: 0

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

  1. query := bson.M{
  2. "datetime": bson.M{
  3. "$gt": startDate,
  4. "$lt": endDate,
  5. },
  6. "device_alias": bson.M{"$in": aliases},
  7. }
英文:

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

  1. query := bson.M{
  2. "datetime": bson.M{
  3. "$gt": startDate,
  4. "$lt": endDate,
  5. },
  6. "device_alias":bson.M{"$in": aliases},
  7. }

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:

确定