2

I'm using nodejs to query mongodb and want to output json with customized field names.

For example, original json from MongoDB maybe

    {id:1, text:"abc"}

I'd like to output it as

    {ObjectID:1, DisplayText:"abc"};

I understand MongoDB has the $project operator in its aggregate framework but not sure how to use them in NodeJS.

The mongodb nodejs packages I'm using are

    var mongo = require('mongodb');
    var monk = require('monk');
    var db = monk('server:port/mydb');

Appreciate any advice on this.

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Lee
  • 2,874
  • 3
  • 27
  • 51
  • Maybe this will get you started: http://stackoverflow.com/questions/16252208/how-to-use-regex-in-mongodb-aggregation-query-within-match – John Powell May 30 '14 at 09:28
  • Thanks, John. Would you know which mongodb package to use? I used similar implementation and get TypeError: Object # has no method 'collection'. – Lee May 30 '14 at 09:47

2 Answers2

9

If you are using monk as you appear to be then you can access the underlying node native driver collection type via the .col accessor on your selected collection object:

  var db = require('monk')('localhost/test')
    , collection = db.get('example');

  collection.col.aggregate(
    [
      { "$project": {
        "_id": 0,
        "ObjectID": "$_id",
        "DisplayText": "$text"
      }}
    ],
    function(err,result) {

      console.log( JSON.stringify( result, undefined, 4 ) );

    }
  );

Note that methods such as .aggregate() retrieved in this way are not wrapped in the promise object as the standard monk collection objects are. But at least this shows you how to access and use $project to re-shape your document.

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
  • Thanks, Neil. This seems working though I get a different error: "aggregation result exceeds maximum document size (16MB)", but I believe this should be a separate issue I should work on. – Lee Jun 02 '14 at 02:33
  • 1
    @user3492125 As it stands this is trying to output the whole collection to what is essentially an array, so you probably do not want the whole collection if you are sending a response to the client. There are other approaches but probably most specific to you right now is the [**`$match`**](http://docs.mongodb.org/manual/reference/operator/aggregation/match/) pipeline operator in order to reduce the results. At least you know how to use aggregate with monk now. Feel free to post other questions to stack overflow if you have them. – Neil Lunn Jun 02 '14 at 02:40
  • Neil, you got a sharp mind. That's exactly what I missed out earlier. Thank you. – Lee Jun 02 '14 at 07:31
0

Have a look at Virtuals in Mongoose http://mongoosejs.com/docs/guide.html#virtuals

You could do something like:

someSchema.virtual('text').get(function() {
    return this.DisplayText;
}
knowbody
  • 8,106
  • 6
  • 45
  • 70