显示为子文档

时间:2018-07-12 08:32:22

标签: mongodb

我收藏了。我在此处输入文档代码如下:

{

    "Jid" : "101",
    "JName" : "Artery",
    "ArtNo" : "1",
    "ArtName" : "Nervous",
    "CE" : "CE1",
    "Dept" : "Pagination",
    "CEInDate" : "2018-07-10",
    "DeptInDate" : "2018-07-10"
}
{

    "Jid" : "101",
    "JName" : "Artery",
    "ArtNo" : "2",
    "ArtName" : "Blood",
    "CE" : "CE2",
    "Dept" : "CopyEditing",
    "CEInDate" : "2018-07-10",
    "DeptInDate" : "2018-07-10"
}

我想要如下所示的输出。请帮助我,这是mongodb的新手

{
   "Jid" : "101",
   "JName" : "Artery"
    Article:[
          {
            "ArtNo" : "1",
            "ArtName" : "Nervous"
                    Department:{
                      "CE" : "CE1",
                      "Dept" : "Pagination",
                       "CEInDate" : "2018-07-10",
                       "DeptInDate" : "2018-07-10"
                               }
           },

     {
        "ArtNo" : "2",
        "ArtName" : "Blood"
              Department: {
                       "CE" : "CE2",
                       "Dept" : "CopyEditing",
                        "CEInDate" : "2018-07-10",
                        "DeptInDate" : "2018-07-10"
                          }
    }
        ]
}

1 个答案:

答案 0 :(得分:0)

db.getCollection("collection").aggregate(

    // Pipeline
    [
        // Stage 1
        {
            $group: {
                _id: {
                    Jid: '$Jid',
                    JName: '$JName'
                },
                Article: {
                    $addToSet: {
                        "ArtNo": "$ArtNo",
                        "ArtName": "$ArtName",
                        "Department": {
                            "CE": "$CE1",
                            "Dept": "$Dept",
                            "CEInDate": "$CEInDate",
                            "DeptInDate": "$DeptInDate"
                        }
                    }
                }
            }
        },

    ]



);