如何获取父文档的所有字段?

时间:2019-04-30 07:20:22

标签: mongodb mongodb-query aggregation-framework aggregate aggregation

我尝试使用 $ group 提取父文档的所有字段,但只发送特定的字段。

另一个问题。如何使用“ $ project”获取父文档的所有字段?

收藏“ 机会
文件#1

{
    "_id" : ObjectId("5c42b737cd94891a57fbf33e"),
    "accountId" : [
         ObjectId("5c29f198b248d845931a1830"),
         ObjectId("5c29f198b248d845931a1831"),
    ]
    "name" : "OppNewTest01",
    "value" : 10000,
    "status" : "open",
}

收藏“ 帐户
文件#1

{        
     "_id" : ObjectId("5c29f198b248d845931a1830"),
     "name" : "MyTestAcc",
     "phone" : "7845124578",
}

我的MongoDB查询,

con.collection('opportunity').aggregate([
    {
        $unwind: "account"
    },
    {
        $lookup: {
            from: 'account',
            localField: 'accountId',
            foreignField: '_id',
            as: 'accounts',
        },
    },
    {
        $unwind: '$accounts'
    },
    {
        $group: {
            "_id": "$_id",
            "account": { "$push": "$accounts" }
        }
    },
    ]).toArray((err, res) => {
        cbFun(res, err);
});
上述查询的

输出

{
    "_id" : "5c42b737cd94891a57fbf33e",
    "account": [
         {        
            "_id" : ObjectId("5c29f198b248d845931a1830"),
            "name" : "MyTestAcc",
            "phone" : "7845124578",
         },
         {        
            "_id" : ObjectId("5c29f198b248d845931a1831"),
            "name" : "MyTestAcc1",
            "phone" : "7845124579",
         },
    ]
}

我想在输出下方显示

{
    "_id" : "5c42b737cd94891a57fbf33e",
    "accountId" : [
           ObjectId("5c29f198b248d845931a1830"),
           ObjectId("5c29f198b248d845931a1831"),
    ],
    "name" : "OppNewTest01",
    "value" : 10000,
    "status" : "open",
    "account": [
         {        
            "_id" : ObjectId("5c29f198b248d845931a1830"),
            "name" : "MyTestAcc",
            "phone" : "7845124578",
         },
         {        
            "_id" : ObjectId("5c29f198b248d845931a1831"),
            "name" : "MyTestAcc1",
            "phone" : "7845124579",
         },
    ]
}

我试图获取以上输出但没有得到。

1 个答案:

答案 0 :(得分:1)

您在$ group时只是丢失了这些数据,请在该阶段保存这些字段以保留它们。

    {
        $group: {
            "_id": "$_id",
            "account": { "$push": "$accounts" },
            value: {$first: "$value"},
            status: {$first: "$status},
            name: {$first: "$name"},
            accountId: {$push: "$accountId},
        }
    }

EDIT:
[
    {
        $group: {
            "_id": "$_id",
            "accounts": { "$push": "$accounts" },
            "doc": {$first: "$$ROOT"},
        }
    },
    {
        $addFields: {
              "doc.accounts" :"$accounts"
        }
     }
]