dpolicastro
dpolicastro

Reputation: 1519

How can I insert and find an object inside a multiple nested array in MongoDB?

I'm having a problem trying to insert an object inside a multiple nested array in my mongoose schema for mongoDB. I have the following structure:

{
    contries: [{
        name: 'String',
        states: [{
            name: 'String',
            cities: [{
                name: 'String',
                regions: [{
                    name: 'String',
                    habitants: [{
                            name: 'String',
                            age: Number
                        },
                        {
                            name: 'String',
                            age: Number
                        }
                    ]
                }]
            }]
        }]
    }]
}

1 - Imagine I want to insert habitants inside a specific region in a specific city and so on, how can I build the query?

2 - If a recieve this entire json object as a request, I need to check if any of the country, city, state or region exist, if none of them exist, I need to create and insert the habitants in the array.

3 - If I need to get only the habitants array from one specific region in a specific city, how can I use projection operator to filter this? (I want mongo to filter, not the application).

4(BONUS) - Habitants array only contain the object Id of a habitant object, just need to use populate?

Upvotes: 1

Views: 243

Answers (1)

kailniris
kailniris

Reputation: 9536

Its not possible to do these things with mongodb.
According to mongodb docs its not possible to travers more then 1 dept in arrays.

The positional $ operator cannot be used for queries which traverse more than one array, such as queries that traverse arrays nested within other arrays, because the replacement for the $ placeholder is a single value.

However you can use another schema like:
Bring the Habitant doc to top level
This is a Habitant doc:

{
  name: 'hab1',
  country: 'country1',
  city: 'cit1',
  region: 'region1'
}

With this schema You can normalize or denormalize data and can query and project data easily.

UPDATE: This mongodb limitation seems to resolve in the near future https://jira.mongodb.org/browse/SERVER-27089

Upvotes: 1

Related Questions