In NodeJS, how to output results from mongodb with different field names?(在 NodeJS 中,如何从 mongodb 输出具有不同字段名称的结果?)
问题描述
我正在使用 nodejs 查询 mongodb 并希望输出带有自定义字段名称的 json.
I'm using nodejs to query mongodb and want to output json with customized field names.
例如,可能是来自 MongoDB 的原始 json
For example, original json from MongoDB maybe
{id:1, text:"abc"}
我想把它输出为
{ObjectID:1, DisplayText:"abc"};
我了解 MongoDB 在其聚合框架中有 $project 运算符,但不确定如何在 NodeJS 中使用它们.
I understand MongoDB has the $project operator in its aggregate framework but not sure how to use them in NodeJS.
我使用的 mongodb 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.
推荐答案
如果您使用的是和尚,那么您可以通过 .col
访问器访问底层节点本机驱动程序集合类型在您选择的集合对象上:
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 ) );
}
);
注意 .aggregate()
以这种方式检索的不会像标准的僧侣集合对象那样包装在承诺对象中.但至少这向您展示了如何访问和使用 $project
重新塑造您的文档.
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.
这篇关于在 NodeJS 中,如何从 mongodb 输出具有不同字段名称的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 NodeJS 中,如何从 mongodb 输出具有不同字段名称的结果?


基础教程推荐
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 直接将值设置为滑块 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01