How to flatten a subdocument into root level in MongoDB?

后端 未结 6 1020
一个人的身影
一个人的身影 2020-12-01 13:53

For example, if I have a document like this

{
  a: 1,
  subdoc: {
          b: 2,
          c: 3
          }
}

How can I convert it into a

6条回答
  •  余生分开走
    2020-12-01 14:24

    I guess the easiest way is altering the result after it returns, using map.

    collection.mapFunction = function(el) {
      el.b = el.subdoc.b;
      el.c = el.subdoc.c
      delete(el.subdoc);
      return el;
    }
    
    ...
    
    var result = await collection.aggregate(...).toArray();
    result = result.map(collection.mapFunction);
    

提交回复
热议问题