Home > database >  Mongodb aggregation use document field as key for array result instead of incremental numbers
Mongodb aggregation use document field as key for array result instead of incremental numbers

Time:03-17

My aggregation give me this results in mongodb query

{"_id" : 1, "color" : "red", "year" : 2019},
{"_id" : 2, "color" : "blue", "year" : 2018},
{"_id" : 3, "color" : "green", "year" : 2020}

and in php I have the results like this:

array(3) {
    [0] => array(3) {
        ["_id"] => int(1),
        ["color"] => string(3) "red"
        ["year"] => int(2019),
    },
    [1] => array(3) {
        ["_id"] => int(2),
        ["color"] => string(4) "blue"
        ["year"] => int(2018),
    },
    [2] => array(3) {
        ["_id"] => int(3),
        ["color"] => string(5) "green"
        ["year"] => int(2020),
    }
}

what I need is to have it like this:

array(3) {
    ["red"] => array(3) {
        ["_id"] => int(1),
        ["color"] => string(3) "red"
        ["year"] => int(2019),
    },
    ["blue"] => array(3) {
        ["_id"] => int(2),
        ["color"] => string(4) "blue"
        ["year"] => int(2018),
    },
    ["green"] => array(3) {
        ["_id"] => int(3),
        ["color"] => string(5) "green"
        ["year"] => int(2020),
    }
}

So in words, I want to return the documents results as an array with the key as the $color of each document. What I did is to loop one time throw the results and copy in a new array as follow:

newArray = [];

foreach($query as $doc){
    $newArray[$doc['color']] = $doc;
}

and now newArray have the structure I need but I want to achieve it directly from mongo so the php server side not have to do the work when there are thousand of documents.

CodePudding user response:

It sounds like adding these two steps to your aggregation can do the job:

{$group: {_id: 0, arr: {$push: {k: '$color', v: {_id: '$_id', color: '$color', 
    year: '$year'}}}}},
{$project: {res: {$arrayToObject: '$arr'}, _id: 0}}

Returning:

{
"res" : {
    "red" : {
        "_id" : 1,
        "color" : "red",
        "year" : 2019
    },
    "blue" : {
        "_id" : 2,
        "color" : "blue",
        "year" : 2018
    },
    "green" : {
        "_id" : 3,
        "color" : "green",
        "year" : 2020
    }
}
}
  • Related