2

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.

icza
  • 389,944
  • 63
  • 907
  • 827
Gal Sosin
  • 714
  • 7
  • 27

1 Answers1

1

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"}
icza
  • 389,944
  • 63
  • 907
  • 827