Home > other >  Find a document via mongo-driver golang with nested array
Find a document via mongo-driver golang with nested array

Time:12-07

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.

CodePudding user response:

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