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.

1 Answer 1

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"}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.