Gal Sosin
Gal Sosin

Reputation: 734

Find a document via mongo-driver golang with nested array

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.

Upvotes: 2

Views: 1890

Answers (1)

icza
icza

Reputation: 417462

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

Upvotes: 1

Related Questions