D
D
Dmitry Sudarkin2017-10-31 11:59:27
Database
Dmitry Sudarkin, 2017-10-31 11:59:27

How to change sorting by MongoDB document in Laravel?

Hello.
Tired of looking for information on changing sorting ...
In general, there are documents

{
    "_id": ObjectId("1974a8d27745ffb9644da8e1"),
    "sort": 0
}
{
    "_id": ObjectId("2974a8d27745ffb9644da8e2"),
    "sort": 1
}
{
    "_id": ObjectId("3974a8d27745ffb9644da8e3"),
    "sort": 2
}

Now I need to change the order of the "sort" numbers
I get the id array in the correct order
$ids = [
    "2974a8d27745ffb9644da8e2",
    "3974a8d27745ffb9644da8e3",
    "1974a8d27745ffb9644da8e1"
]

And saving the new order should look something like this
foreach ($ids as $id) {
    $each[] = ['_id' => new \MongoDB\BSON\ObjectID($id)];
}
$result = Modules::update([
    'sort' => [
        '$each' => $each,
        '$sort' => 1
    ]
]);

But it doesn't work.
Of course, you can iterate through all the documents and update each one individually, but this may take longer to process than it should.
foreach ($ids as $sort=>$id) {
    Modules::where([
        '_id' => $id
    ])->update([
        'sort' => $sort
    ]);
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Gornostaev, 2019-08-05
@spongebozz

Under these conditions, any will do.

D
Dmitry Sudarkin, 2017-10-31
@GrozInventor

I love it when the complexity of the question is marked "Elementary", while not answering the question itself))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question