1

I'm new to MongoDB and I'm trying to figure out how to query over a structure that is recursive, that means that an Object X with specific attributes can hold a list ob Object X, this is an example of that in JSON:

{
  "type": "A",
  "subtype": "A1",
  "children": [
    {
      "type": "B",
      "subtype": "B1"
    },
    {
      "type": "B",
      "subtype": "B2",
      "children": [
        {
          "type": "D",
          "subtype": "D1"
        },
        {
          "type": "D",
          "subtype": "D2"
        }
      ]
    },
    {
      "type": "C",
      "subtype": "C1"
    }
  ]
}

The query I need to figure out, is how to check if a document contains descendant documents with specific attribute values. These are samples of such queries:

  1. Does a document with "type" = "A" contain a document with "type" = "B" (on the example there are 2 subdocuments as direct children for the document with "type" = "A")

  2. Does a document with "type" = "A" contain a document with "type" = "D" (I need to check for any descendants, in the example document with "type" = "A" contains a child with "type" = "D" that contains 2 childs with "type" = "D, so yes A contains D).

Results could be the decendant subdocuments or a boolean (true if the query finds any descendant with that specific type).

Is checking stuff like that possible in MongoDB? Thanks.

Pablo Pazos
  • 3,080
  • 29
  • 42
  • 1
    Possible?, Yes. Practical? No. Nesting arrays is a really bad idea in general, and pretty much has none of the advantages you might of thought that it did. Aside from the linked existing answer, you would do well to read [Updating a Nested Array with MongoDB](https://stackoverflow.com/a/23577266/2313887) and [Find in Double Nested Array MongoDB](https://stackoverflow.com/questions/29071748/find-in-double-nested-array-mongodb) for a bit more context on what you are actually jumping into and how you really can handle this data better. – Neil Lunn Mar 22 '19 at 06:30

0 Answers0