'laravel pluck function doesn't give the result i want
My mongodb collection;
[
{
"_id" : ObjectId('623204a7278eb2d65165a604'),
"name" : "One",
"data" : {
"by" : ObjectId('623204d1e0b39813dec5f9ca')
},
},
{
"_id" : ObjectId('623205156949c5e3ab47a94e'),
"name" : "Two",
"data" : {
"by" : ObjectId('6232051cc76f3fcc90351784')
}
}
]
I using jenssegers/laravel-mongodb package. This is how I get data:
$array = MyCollection::where(...)
->get(['_id', 'data.by']);
I am doing the following operation on array:
$array->pluck('data.by');
This gives the output:
[{"$oid": "623204d1e0b39813dec5f9ca"},{"$oid": "6232051cc76f3fcc90351784"}]
I want to data.by ids array: ['623204d1e0b39813dec5f9ca' , '6232051cc76f3fcc90351784'];
Solution 1:[1]
I'm not completely sure, but I think you can get your desired output with map()
These 3 lines should do the same thing.
$array->pluck('data.by')->map(function ($item) { return $item->{'$oid'}; });
$array->pluck('data.by')->map(fn ($item) => $item->{'$oid'});
$array->pluck('data.by')->map->{'$oid'};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | IGP |
