如何在 MongoDB 中将子文档展平为根级别? [英] How to flatten a subdocument into root level in MongoDB?

查看:23
本文介绍了如何在 MongoDB 中将子文档展平为根级别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

For example, if I have a document like this

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

How can I convert it into a format like this? (without using project)

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

解决方案

You can use MongoDB projection i.e $project aggregation framework pipeline operators as well. (recommended way). If you don't want to use project check this link

db.collection.aggregation([{$project{ . . }}]);

Below is the example for your case:

db.collectionName.aggregate
([
    { $project: { a: 1, 'b': '$subdoc.b', 'c': '$subdoc.c'} }
]);

Gives you the output as you expected i.e.

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

这篇关于如何在 MongoDB 中将子文档展平为根级别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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