Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update MongoDB field using value of another field #352

Open
zerg4000 opened this issue Aug 21, 2022 · 1 comment
Open

Update MongoDB field using value of another field #352

zerg4000 opened this issue Aug 21, 2022 · 1 comment
Labels
type:enhancement Enhancement

Comments

@zerg4000
Copy link

Starting from MongoDB v4.2 we can Updates with Aggregation Pipeline (see https://www.mongodb.com/docs/manual/tutorial/update-documents-with-aggregation-pipeline/)
But with yii2-mongodb query like this

Model::updateAll([
    ['$set' => ['new_field => '$old_field']]
]);

or this

$collection = Yii::$app->mongodb->getCollection('collectionName');        
$collection->update([], [['$set' =>  ['new_field => '$old_field']]]);

causes MongoDB Exception

What steps will reproduce the problem?

$collection = Yii::$app->mongodb->getCollection('collectionName');        
$collection->update([], [['$set' =>  ['new_field => '$old_field']]]);

What's expected?

Update all rows and add new field using value of another field

What do you get instead?

MongoDB Exception – yii\mongodb\Exception
Modifiers operate on fields but we found type array instead. For example: {$mod: {: ...}} not {$set: [ { $set: { user_uid: "$owner" } } ]}

Additional info

I think problem in yii\mongodb\Command::addUpdate method and can fixed:

        if ($options['multi']) {
            $keys = array_keys($document);
            if (!empty($keys) && strncmp('$', $keys[0], 1) !== 0) {
                $document = ['$set' => $document];
            }
        }

change to

        if ($options['multi'] && \yii\helpers\ArrayHelper::isAssociative($document)) {
            $keys = array_keys($document);
            if (!empty($keys) && strncmp('$', $keys[0], 1) !== 0) {
                $document = ['$set' => $document];
            }
        }
Q A
Yii version 2.0.45
Yii MongoDB version 2.1.12
MongoDB server version 5.0.6
PHP version 8.1.7
Operating system Alpine Linux
@samdark samdark added the type:enhancement Enhancement label Aug 22, 2022
@samdark
Copy link
Member

samdark commented Aug 22, 2022

Interesting. Do you have time to prepare a pull request with a fix and some tests?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type:enhancement Enhancement
Projects
None yet
Development

No branches or pull requests

2 participants