Nate Stemen
Nate Stemen

Reputation: 1311

get data out of array in mongo query

I have a query (db.vehicles.find( {}, { 'cars.model': 1 } )) that gets me some data that looks like

{
  _id: ObjectId(...),
  cars: [
    {
      model: 'foo'
    }
  ]
}
{
  _id: ObjectId(...),
  cars: [
    {
      model: 'foo'
    },
    {
      model: 'bar'
    }
  ]
}

but I would really like to to have it return something like

{
  _id: ObjectId(...),
  cars: [ 'foo' ]
}
{
  _id: ObjectId(...),
  cars: [ 'foo', 'bar' ]
}

or at least something where the data isn't as nested. I can't seem to figure out how to do this with mongo as I'm relatively new to it.

I'm also wondering if maybe you aren't supposed to do this sort of thing in mongo as it seems most queries kind of leave the data as is, but just get you the data you have, but filtered. Maybe I'm bringing too many PostgreSQL ideas to my attempt of a mongo query.

Upvotes: 0

Views: 46

Answers (1)

Vihar Manchala
Vihar Manchala

Reputation: 837

Try below query

db.getCollection('vehicles').aggregate([
    {
        $addFields: {
            cars : '$cars.model'
        }
    }
])

Upvotes: 1

Related Questions