0

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.

4
  • @ViharManchala what i asked for is json format though, is it not? Commented Mar 8, 2019 at 18:07
  • What your query's saying is find a car with a model value of 1. But your models' values are strings Commented Mar 8, 2019 at 18:12
  • @jstarnate i think the query is finding all cars, and the second argument (the projection) is saying give me the cars model Commented Mar 8, 2019 at 18:14
  • Since the cars property's value is an array, use map() to return each of the models value Commented Mar 8, 2019 at 18:22

1 Answer 1

1

Try below query

db.getCollection('vehicles').aggregate([
    {
        $addFields: {
            cars : '$cars.model'
        }
    }
])
Sign up to request clarification or add additional context in comments.

2 Comments

Wonderful, thank you so much! I also had to add { $project: { 'cars.model': 1 } } in order to ignore all the other fields, but overall great. Is there a reason you use getCollection('vehicles') over just doing db.vehicles.aggregate?
You can use db.vehicles.agrregate too. There is no difference. My tool computes db.getCollection('vehicles').aggregate by default

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.