What is the better and optimal way to find the key (can be n-level nested ) is present in the mongodb collection?

Let us take my document in collection looks like this bellow

    "data": [
            "MainId": 1111,
            "firstName": "Sherlock",
            "lastName": "Homes",
            "categories": [
                    "CategoryID": 1,
                    "CategoryName": "Example"
            "MainId": 122,
            "firstName": "James",
            "lastName": "Watson",
            "categories": [
                    "CategoryID": 2,
                    "CategoryName": "Example2"
    "messages": [], // blank json
    "success": true // boolean value

so i need to search whether the key exists CategoryID in the document or not , It is just an example my search key can be anything and can be nested to any level

what is an better and optimal way to find whether the key exists or not ?
Note: each document structure might vary so need to find whether the key is present in the whole collection or not

i can iterate through all the documents in the collection and recursively go as deep as inside to check the existing of the key but that is brute force solution how can i optimise it…?

What i need is:

  • MongoDb aggregation query if exists
  • OrElse any other way to do it in better and optimal way

Hi @Divakar_V1 and welcome to MongoDB community forums!!

As you are aware that Embedding documents in MongoDB gives you the flexibility to model the data in an efficient manner. Please correct me if my understanding of your use-case is not right or if I am missing something, your document schema has long nested levels which could make the use of dot notation mechanism to access the embedded documents difficult and as you mentioned would be a brute force method.

To avoid this, you can make use of the Extended Reference Patten to model the data and test your use-case as per your requirements to see if this solves your purpose.

Let us know if the above solution works for you.


1 Like

@Aasawari Thanks for your answer but i need to do without altering the document