19

what is the mongodb equivalent of the MySQL query

SELECT username AS  `consname` FROM  `consumer`
Salvador Dali
  • 214,103
  • 147
  • 703
  • 753
sajith
  • 2,564
  • 8
  • 39
  • 57
  • 3
    aggregation framework $proejct is the only way – Sammaye Nov 13 '13 at 14:03
  • 1
    Best to just fix up the data using whatever client/driver you're using. Some can do this as a feature of the driver. – WiredPrairie Nov 13 '13 at 14:32
  • 1
    `db.consumer.find().toArray().map(function (doc) { doc.consname=doc.username; delete doc.username; return doc; });` – hgoebl Nov 13 '13 at 14:47
  • @hgoebl: find() returns a collection, and there is no toArray method (at least in Meteors mongodb version 2). But you can do a forEach on the collection. – westor Oct 09 '15 at 06:55
  • @westor possible that I'm wrong or the `toArray()` is only in mongo shell or in an older version of the native driver. Thanks for your hint! – hgoebl Oct 09 '15 at 12:34
  • @westor: what's up with Meteor? The OP asked about MongoDB, not Meteor. find() returns a cursor, which has a [`map` method](http://mongodb.github.io/node-mongodb-native/3.1/api/Cursor.html#map). – Dan Dascalescu Aug 11 '18 at 23:35

2 Answers2

21

As it was mentioned by sammaye, you have to use $project in aggregation framework to rename fields.

So in your case it would be:

db.consumer.aggregate([
    { "$project": {
        "_id": 0,
        "consname": "$username"
    }}
])

Cool thing is that in 2.6.x version aggregate returns a cursor which means it behaves like find.

You might also take a look at $rename operator to permanently change schema.

Salvador Dali
  • 214,103
  • 147
  • 703
  • 753
  • 1
    This helped me in flattening array values from `$lookup` aggregate function after spending a few hours of search. Thanks :) – Stranger Jul 12 '19 at 21:51
-1

Salvador Dali's answer is fine, but not working in meteor versions before 3.0. I currently try meteor, and their build in mongodb is in version 2. The way I solved this is like this:

var result = []:
db.consumer.forEach( function(doc) {
   result.push({
     consname:doc.username
   });
});
westor
  • 1,426
  • 1
  • 18
  • 35