arcyqwerty
arcyqwerty

Reputation: 10675

MongoDB similar to SQL "AS"

How does one rename the columns on a query to mongodb?

This should not permanently alter the columns for future queries or in the database (non-persistent) but rather just for the query

The functionality that I am looking for is similar to SQL's 'AS' as used in SELECT col1 AS a, col2 as b, col1 as c FROM table

I am aware that this can be rather trivially processed by the application but was just curious as to how this is implemented in mongodb

Upvotes: 0

Views: 582

Answers (2)

Eric
Eric

Reputation: 2884

The aggregation framework can achieve a similar functionality:

db.table.aggregate({ $project: { a: '$col1', b: '$col2', c: '$col3' }})

It is also possible to filter on a certain conditions by adding a $match in the pipeline:

db.table.aggregate(
  { $match: {'col1': 'value'} },
  { $project: { a: '$col1', b: '$col2', c: '$col3' }}
)

That said, as the aggregation framework has some limitations, processing this in the application should be a better choice.

Upvotes: 4

Mihai
Mihai

Reputation: 2760

I don't think that's possible because when retrieving the results the mongo driver maps them to a existing class. if you change the name of the fields the mapping won't be possible

Upvotes: 0

Related Questions