考虑以下代码,我使用它从本地 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/