1

I have a model:

const schema = new mongoose.Schema({
  country: { type: String },
  code: { type: String },
  region: [{
    name: { type: String },
    city: [{
      name: { type: String },
      latitude: { type: String },
      longitude: { type: String },
    }],
  }],
})

I need to get list of region -> city -> name (list of sities names) In the begining I tried a query to get list of (Array)city

const list = await Model.findOne(
  { $and: [{ code: req.params.code }, { 'region.name': 'Harjumaa' }] },
  { 'region.city.name': 1 },
)

And receive this data:

enter image description here

Then I search list of regions I send query:

Model.findOne({ code: req.params.code }, { region: 1 })

And receive data like this:

enter image description here

I want to get list of cities names in the same format.

My data sample:

{
  "country": "Estonia",
  "code": "ee",
  "region": [
    {
      "name": "Harjumaa",
      "city": [
        {
          "name": "Aegviidu vald",
          "latitude": "59.27941132",
          "longitude": "25.62571907"
        },
        {
          "name": "Anija vald",
          "latitude": "59.27643967",
          "longitude": "25.48167992"
        }
      ]
    }
  ]
}
2
  • can you provide sample data Commented Feb 2, 2019 at 9:05
  • @AshayMandwarya Add to body Commented Feb 2, 2019 at 9:10

1 Answer 1

1

$project with $region.city.name path will give you an array of arrays since you have two levels of nesting. To fix that you can use $reduce with $concatArrays which will flatten your final result into single array, try:

Model.aggregate([
    {
        $match: { code: "ee" }
    },
    {
        $project: {
            cityNames: {
                $reduce: {
                    input: "$region.city.name",
                    initialValue: [],
                    in: { $concatArrays: [ "$$this", "$$value" ] }
                }
            }
        }
    }
])
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.