I want to insert a array to object as embed in collection mongodb like this and below image :
[
[
"lat"=> 59.56555555455,
"lon"=> 35.54598994564,
"type"=> "manual"
],...
]
To achieve it I wrote below code. When I use foreache
it did work but when I want to use InsertMany
with raw query log it shows me objects inserted but when I check the database no change are committed!!! Where is my mistake?
log:
InsertManyResult {#302
-writeResult: WriteResult {#301}
-insertedIds: array:3 [
0 => ObjectId {#297
+"oid": "5bcd6d636925022398005981"
}
1 => ObjectId {#281
+"oid": "5bcd6d636925022398005982"
}
2 => ObjectId {#298
+"oid": "5bcd6d636925022398005983"
}
]
-isAcknowledged: true
}```
code:
$userTraffic = Auth::user()->userTraffic()->firstOrFail();
if ($userTraffic) {
$userTraffic->traffics()->raw( function ( $collection ) use ($traffic) {
$data= $collection->insertMany($traffic);
dd($data);
return $data;
});
/* foreach ($traffic as $field) {
$userTraffic->traffics()->create($field);
}*/
return response(['status'=>true,'UserID:'=> Auth::id(),'data'=>$traffic,'insert'=>$userTraffic], 200);
}
else return response(['status'=>false,'message'=>'traffic\'s user not found'], 404);
}
--answer:
just use $userTraffic->traffics()->createMany($traffic);
with no problem :) ;