Mongo db:以.map .join方式转换字段

时间:2017-02-23 18:04:14

标签: mongodb projection

以下是一个示例集合:

[
 {
  id: 1,
  users: [
   {name: 'John Doe'}, {name: 'Ruth Paulson'}
  ]
 },
 {
  id: 2,
  users: [
   {name: 'Meg Alosaurus'}, {name: 'Ruth Paulson'}
  ]
 }

]

如何编写查询以获得此类结果:

[
  { id: 1, usernames: ['John Doe', 'Ruth Paulson'] }
  { id: 2, usernames: ['Meg Alosaurus', 'Ruth Paulson'] }
]

或者,或者:

[
  { id: 1, usernames: 'John Doe, Ruth Paulson'},
  { id: 2, usernames: 'Meg Alosaurus, Ruth Paulson'}
]

在javascript中,我会这样做:

collection.map(record => ({
  id: record.id,
  usernames: record.map(user => user.name)/*.join(', ')*/
}));

(注意:我对mongo db很新。我已经尝试了一些像$ project,mapReduce,$ concat这样的结构,但无法得到我想要的结果)

1 个答案:

答案 0 :(得分:1)

以下是使用聚合的查询。

/* 1 */
{
    "_id" : 2,
    "usernames" : [ 
        "Meg Alosaurus", 
        "Ruth Paulson"
    ]
}

/* 2 */
{
    "_id" : 1,
    "usernames" : [ 
        "John Doe", 
        "Ruth Paulson"
    ]
}

<强>输出: -

@Injectable()
export class CustomHttp extends Http {

  constructor (backend: XHRBackend, options: RequestOptions) {
    let token = localStorage.getItem('auth_token'); 

    options.headers.set('Authorization', `Bearer ${token}`);
    super(backend, options);
  }

  request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> {
    let token = localStorage.getItem('auth_token');
    if (typeof url === 'string') { 
      if (!options) {
        // let's make option object
        options = {headers: new Headers()};
      }
      options.headers.set('Authorization', `Bearer ${token}`);
    } else {
      url.headers.set('Authorization', `Bearer ${token}`);
    }
    return super.request(url, options).catch(this.catchAuthError(this));
  }

  private catchAuthError (self: CustomHttp) {
    return (res: Response) => {
     if (res.status === 401 || res.status === 403) {

     }

      }
      return Observable.throw(res);
    };
  }
}