How to create mongodb collection on runtime while executing Yii2 code?

181 views Asked by At

I need to create mongodb collection while executing code, by checking whether the collection is exists or not.

I tried below things

Yii::$app->db->createCommand()-> createCollection("collection_name");

but collection not created.

Please help.

1

There are 1 answers

1
Mahesh On

Issue resolved..

Yii::$app->db->createCommand()->createCollection("collection_name")->execute();

and index will added for collection as,

$collectionName = Yii::$app->db->getCollection("collection_name");
$collectionName->createIndexes([
'key' => ['id' => 'int'],
'name' => 'id_index'
],
[
'key' => ['id' => 'int', 'category' => 'text'],
'name' => 'id_category_index',
]);