node.js - 如何在通过使用 MongoDB-Node.JS native 驱动器查询从 MongoDB 获取字段时重命名/别名字段?

标签 node.js mongodb mongodb-query

考虑以下代码,我使用它从本地 MongoDB 服务器获取数据。

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'
      });
    });
  });
});

现在,我想在仅检索时重命名字段名称(不在数据库中),例如使用上面的代码,我在返回的对象 doc 中有一个名为 b 的字段 我希望它是 baseID 而不是 b

有什么办法吗?

注意:我无法对检索到的对象 doc 采取操作来重命名字段,例如重命名 JSON 键。我希望它被查询,MongoDB 也一样。

最佳答案

使用 aggregate framework of MonogDB (但你需要upgrade MongoDB 服务器实例>= 2.1)。

以下是上面例子的灵魂提示

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);
          });
        });
    });
});

输出:

[ { a: 1, baseID: 1 },
  { a: 2, baseID: 2 },
  { a: 3, baseID: 3 }]

关于node.js - 如何在通过使用 MongoDB-Node.JS native 驱动器查询从 MongoDB 获取字段时重命名/别名字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15872301/

相关文章:

mongodb - 嵌入文档中的批量更新

mongodb - 字段名称中未捕获的异常 : can't have .

node.js - python -i : run and enter interactive mode?的node.js模拟是什么

linux - 添加 .env 变量以运行给定命令

如果选择标记分片键,MongoDB 仅将数据存储到主分片

mongodb - 选择按字段分组的文档

mongodb - 如何仅查找所有嵌入属性在 mongodb 中匹配的嵌入事件?

javascript - axios get 请求的控制台日志放在哪里?

node.js - socketIO客户端默认监听什么端口?

Java/WildFly/MongoDB/JAAS - 身份验证始终返回 403 - 禁止