kratos
kratos

Reputation: 2495

How to implement the following Mongo pseudocode in Laravel?

I want to implement:

db.lawcases.find().snapshot().forEach(
    function (elem) {
        db.lawcases.update(
            {
                _id: elem._id
            },
            {
                $set: {
                    name: elem.firstname + ' ' + elem.lastname
                }
            }
        );
    }
);

I am using the Laravael MongoDB package which allows me to do raw queries as it explains in https://github.com/jenssegers/Laravel-MongoDB#raw-expressions.

I have so far:

$lawCases =  \DB::connection('mongodb')->collection('lawcases')->raw(function($collection)
        {
            return $collection->find();
        });



        foreach($lawCases as $case){
                    //DO SOMETHING

            }

But am needing a bit of help as I do not know how to persist the change. I feel I am not doing it right.

Upvotes: 0

Views: 267

Answers (1)

Taha Paksu
Taha Paksu

Reputation: 15616

Use it like you use Laravel's Database usage:

<?php

// get the cases first
$lawCases = \DB::connection('mongodb')
    ->collection('lawcases')
    ->get();

// update each record
foreach($lawCases as $case)
{
    \DB::connection('mongodb')
    ->collection('lawcases')
    ->where([
        "_id" =>  $case["_id"]
    ])
    ->update([
        "name" => $case["firstname"] . " " $case["lastname"]
    ]);
}

Upvotes: 1

Related Questions