Searching dynamic embedded documents

I have a collect that has a meta field with can contain an array of key/value pairs. The key could be any string and the value could be any string.


"meta": {
  "key2": "value2",
  "key1": "value1",
  "two words": "value1  value2",
  "foo": "bar"

I’m wondering if I can do some advanced searches like:

  1. Find documents where the meta key contains the word “title” (doesn’t matter what the value is).
  2. Find documents where the meta value contains the word “red” (doesn’t matter what the key is).
query = { "meta.title" : { "$exists" : true } }
collection.find( query )

I do not know but with Building with Patterns: The Attribute Pattern | MongoDB Blog it should be eazy.

Thanks, but I need to use Atlas search because that is where the indexes are. Also, I want to search the key for a word. For example, if I search “title” it could find meta keys just as “Title”, “Movie Title”, etc.

What ever you use for search using the Attribute Pattern will simply your life.

It will be hard to define an index if you have dynamic field names. The Attribute Pattern solves that by making your dynamic keys the values of a static field name.

I agree there are better ways to store the data. But this DB pre-dates me. It is 10 years old and refactoring it will be quite a project. We have a solution now by syncing to elasticsearch, but we are looking to move to Atlas search. I’m hoping to find a way to index and query this data without a refactor, but I’m starting to feel that probably is not possible.

Could you use EmbeddedDocument? Where path: meta key, and query: meta value ?