mongodb / laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel (Moloquent)
https://www.mongodb.com/compatibility/mongodb-laravel-integration
MIT License
6.96k stars 1.42k forks source link

Add hasColumn/hasColumns method #3001

Closed Alex-Belyi closed 1 week ago

Alex-Belyi commented 3 weeks ago

Add hasColumn/hasColumns method

Checklist

alcaeus commented 1 week ago

I agree with @GromNaN here. This method is essentially useless, because you're looking for "does any document in this collection have a field with this name". This is not something you should be checking for, and is also an extremely inefficient query as it's usually run unindexed, and thus relies on a collection scan and BSON inspection of every document in the collection.

If there's a specific use case you'd like to change this method for, please share this use case with us, but I don't see any benefit in changing the current implementation.

Alex-Belyi commented 2 days ago

@GromNaN @alcaeus Sorry for late answer.

I want to share example why I added such code.

So I have bitbucket pipelines configured to deploy project to virtual machine There is three options for DB (keep existing, reset all, reset only mysql (keep mongo)).

We use single Laravel project which works with migrations (mysql + mongo)

So there an issue if went to keep mongo DB and reset only mysql

    public function up(): void
    {
        Schema::connection('mongodb')->table('table_name', function (Blueprint $collection) {
            $collection->unique('id');
        });
    }

Will cause an error about existing unique key

so I added some manual 'hasColumn' method to avoid such situation

    public function up(): void
    {
        Schema::connection('mongodb')->table('table_name', function (Blueprint $collection) {
            if (MongoDb::hasColumn('table_name', 'id')) {
                $collection->unique('id');
            }
        });
    }
GromNaN commented 2 days ago

Thanks for taking the time to give a little more context. It seems to me that this use-case does not correspond to the purpose of this method in Laravel. Here are a few comments: