Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename/alias field(s) while fetching it from MongoDB through query using MongoDB-Node.JS native drive?

Consider the following code, which I am using to fetch the data from my local MongoDB server.

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');
var db = new Db('test', new Server('localhost', 27017)); 
db.open(function(err, db) {
  db.createCollection('simple_limit_skip_find_one_query', function(err, collection) {
    assert.equal(null, err);

    collection.insert([{a:1, b:1}, {a:2, b:2}, {a:3, b:3}], {w:1}, function(err, result) {
      assert.equal(null, err); 
      collection.findOne({a:1}, {fields:{b:1}}, function(err, doc) {
        // I got the read document in the object 'doc'
      });
    });
  });
});

Now, I want to rename a field name while retrieving only (not in the DB), for example with the above code, I have a field named b in the returned object doc I want it to be baseID instead of b

Is there any way to do it?

Note: I cannot take action on the retrieved object doc to rename field like JSON key renaming. I want it to be queried and MongoDB will the same.

like image 268
Amol M Kulkarni Avatar asked Apr 08 '13 06:04

Amol M Kulkarni


1 Answers

Use aggregate framework of MonogDB (But you need to upgrade the MongoDB server instance to >= 2.1).

The following is the soultion for the above example

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');
db.open(function (err, db) {
    if (err) console.dir(err);
    db.createCollection('simple_limit_skip_find_one_query', function (err, collection) {
        if (err) console.dir(err);

        collection.insert([{ a: 1, b: 1 }, { a: 2, b: 2 }, { a: 3, b: 3}], { w: 1 }, function (err, doc) {
            if (err) console.dir(err);

            collection.aggregate([
            { $project: {
                a: 1,
                _id:0,
                baseID: "$b"
            }
            }
          ], function (err, doc) {
              if (err) console.dir(err);
              console.log(doc);
          });
        });
    });
});

Output:

[ { a: 1, baseID: 1 },
  { a: 2, baseID: 2 },
  { a: 3, baseID: 3 }]
like image 87
Amol M Kulkarni Avatar answered Sep 23 '22 02:09

Amol M Kulkarni