在NodeJS中,如何从具有不同字段名称的mongodb输出结果? [英] In NodeJS, how to output results from mongodb with different field names?

查看:462
本文介绍了在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');

对此有任何建议。

推荐答案

如果您正在使用monk,那么您可以通过<$访问基础节点本机驱动程序集合类型c $ c> .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() 不包含在promise对象中,因为标准的和尚集合对象是。但至少这会向您展示如何访问和使用 $ 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输出结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆