使用mongo-driver golang通过嵌套数组查找文档。

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

Find a document via mongo-driver golang with nested array

问题

我正在尝试执行一个基本查询,该查询在一个数组中搜索特定值的文档。让我们以以下示例为例:

{
  "metadata": {
    "tenant": [
      "tenant1",
      "tenant2",
      "tenant3"
    ]
  }
}

filter := bson.M{"metadata": bson.M{"tenant": "tenant1"}}

collection := mongo.Database(DB).Collection(Collection)
result := collection.FindOne(context.Background(), filter)

这里的结果是空的,我尝试使用$elemmatch也不起作用。当我将数组从metadata中取出时,它可以工作。

请帮忙解决。

英文:

I'm trying to do a basic query that searches for a document where a specific value is inside an array.
Lets take the following example:

{
  "metadata": {
    "tenant": [
      "tenant1",
      "tenant2",
      "tenant3"
    ]
  }
}

filter := bson.M{"metadata": bson.M{"tenant": "tenant1"}}

collection := mongo.Database(DB).Collection(Collection)
result := collection.FindOne(context.Background(), filter)

The result here is empty, I tried working with $elemmatch it also didn't work.
when I take the array out of metadata it works.

Please help.

答案1

得分: 1

你的filter用于筛选具有metadata字段的文档,该字段是一个带有tenant字段且值为tenant1的文档。

要查找具有metadata字段的文档,该字段是一个文档,并且具有包含tenant1元素的tenant数组,请使用点号将字段名连接起来:

filter := bson.M{"metadata.tenant": "tenant1"}
英文:

Your filter filters for documents that has a metadata field that's a document with a tenant field with tenant1 value.

To find documents that have a metadata field being a document, having a tenant array including the tenant1 element, concatenate the field names with a dot:

filter := bson.M{"metadata.tenant": "tenant1"}

huangapple
  • 本文由 发表于 2021年12月7日 15:05:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/70256096.html
匿名

发表评论

匿名网友

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

确定