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.
My Answer:
"_id": "5f7f7b4b4b3c4d001f7e3b1a",
"name": "John Doe",
"age": 30,
"city": "New York"
}
{
"_id": "5f7f7b4b4b3c4d001f7e3b1b",
"name": "Jane Smith",
"age": 25,
"city": "Los Angeles"
}
{
"_id": "5f7f7b4b4b3c4d001f7e3b1c",
"name": "Alice Johnson",
"age": 35,
"city": "Chicago"
}
{
"_id": "5f7f7b4b4b3c4d001f7e3b1d",
"name": "Bob Brown",
"age": 40,
"city": "Houston"
}
{
"_id": "5f7f7b4b4b3c4d001f7e3b1e",
"name": "Eve Williams",
"age": 28,
"city": "Miami"
}
}
But I want the result to be like this:
{
"5f7f7b4b4b3c4d001f7e3b1a": {
"name": "John Doe",
"age": 30,
"city": "New York"
},
"5f7f7b4b4b3c4d001f7e3b1b": {
"name": "Jane Smith",
"age": 25,
"city": "Los Angeles"
},
"5f7f7b4b4b3c4d001f7e3b1c": {
"name": "Alice Johnson",
"age": 35,
"city": "Chicago"
},
"5f7f7b4b4b3c4d001f7e3b1d": {
"name": "Bob Brown",
"age": 40,
"city": "Houston"
},
"5f7f7b4b4b3c4d001f7e3b1e": {
"name": "Eve Williams",
"age": 28,
"city": "Miami"
}
}
To achieve this result, you can use the $arrayToObject operator in the aggregation pipeline. Here's an example query:
javascript
db.collection.aggregate([
{
$group: {
_id: "$_id",
data: {
$first: {
name: "$name",
age: "$age",
city: "$city"
}
}
}
},
{
$replaceRoot: {
newRoot: {
$arrayToObject: [[{ k: "$_id", v: "$data" }]]
}
}
}
])
This query groups the documents by their _id field and then uses the $arrayToObject operator to convert the grouped data into an object where the _id field is used as the key.
Rate this post
5 of 5 based on 5364 votesComments