Databases and Collections
On this page
Overview
In this guide, you can learn how to use Laravel MongoDB to access and manage MongoDB databases and collections.
MongoDB organizes data in a hierarchical structure. A MongoDB deployment contains one or more databases, and each database contains one or more collections. In each collection, MongoDB stores data as documents that contain field-and-value pairs. In the Laravel Integration, you can access documents through Eloquent models.
To learn more about the document data format, see Documents in the Server manual.
Specify the Database in a Connection Configuration
You can specify a database name that a connection uses in your
application's config/database.php
file. The connections
property
in this file stores all your database connection information, such as
your connection string, database name, and optionally, authentication
details. After you specify a database connection, you can perform
database-level operations and access collections that the database
contains.
If you set the database name in the database
property to the name of a
nonexistent database, Laravel still makes a valid connection. When you
insert any data into a collection in the database, the server creates it
automatically.
The following example shows how to set a default database connection and
create a database connection to the animals
database in the
config/database.php
file by setting the dsn
and database
properties:
'default' => 'mongodb', 'connections' => [ 'mongodb' => [ 'driver' => 'mongodb', 'dsn' => 'mongodb://localhost:27017/', 'database' => 'animals', ], ... ]
When you set a default database connection, the Laravel Integration uses that
connection for operations, but you can specify multiple database connections
in your config/database.php
file.
The following example shows how to specify multiple database connections
(mongodb
and mongodb_alt
) to access the animals
and
plants
databases:
'connections' => [ 'mongodb' => [ 'driver' => 'mongodb', 'dsn' => 'mongodb://localhost:27017/', 'database' => 'animals', ], 'mongodb_alt' => [ 'driver' => 'mongodb', 'dsn' => 'mongodb://localhost:27017/', 'database' => 'plants', ] ], ...
Note
The MongoDB PHP driver reuses the same connection when you create two clients with the same connection string. There is no overhead in using two connections for two distinct databases, so it is unnecessary to optimize your connections.
If your application contains multiple database connections and you want
to store your model in a database other than the default, override the
$connection
property in your Model
class.
The following example shows how to override the $connection
property
on the Flower
model class to use the mongodb_alt
connection.
This directs the Laravel Integration to store the model in the flowers
collection of the plants
database, instead of in the default database:
class Flower extends Model { protected $connection = 'mongodb_alt'; }
Access a Collection
When you create model class that extends
MongoDB\Laravel\Eloquent\Model
, the Laravel Integration stores the model data
in a collection with a name formatted as the snake case plural form of your
model class name.
For example, if you create a model class called Flower
,
Laravel applies the model to the flowers
collection in the database.
Tip
To learn how to specify a different collection name in your model class, see the Change the Model Collection Name section of the Eloquent Model Class guide.
We generally recommend that you use the Eloquent ORM to access a collection
for code readability and maintainability. The following
example specifies a find operation by using the Flower
class, so
Laravel retrieves results from the flowers
collection:
Flower::where('name', 'Water Lily')->get()
Note
Starting in Laravel Integration v4.8, the DB::collection()
method
is deprecated. As shown in the following example, you can use the DB::table()
method to access a MongoDB collection.
If you are unable to accomplish your operation by using an Eloquent
model, you can access the query builder by calling the table()
method on the DB
facade. The following example shows the same query
as in the preceding example, but the query is constructed by using the
DB::table()
method:
DB::connection('mongodb') ->table('flowers') ->where('name', 'Water Lily') ->get()
List Collections
You can take either of the following actions to see information about the collections in a database:
Run a Shell Command
You can list the collections in a database by running the following command in your shell from your project's root directory:
php artisan db:show
This command outputs information about the configured database and lists its
collections under the Table
header. For more information about the db:show
command, see Laravel: New DB Commands
on the official Laravel blog.
Call Database or Schema Methods
You can list the collections in a database by calling the following methods in your application:
DB::listCollections()
: lists information about each collection by using the query builderSchema::getTablesListing()
: lists the name of each collection by using the schema builderSchema::getTables()
: lists the name and size of each collection by using the schema builder
Note
MongoDB is a schemaless database, so the preceding schema builder methods query the database data rather than the schema.
Example
The following example accesses a database connection, then calls the
listCollections()
query builder method to retrieve information about
the collections in the database:
$collections = DB::connection('mongodb')->getMongoDB()->listCollections();
List Collection Fields
You can take either of the following actions to see information about each field in a collection:
Run a Shell Command
You can see a list of fields in a collection by running the following command in your shell from your project's root directory:
php artisan db:table <collection name>
This command outputs each collection field and its corresponding data type
under the Column
header. For more information about the db:table
command, see Laravel: New DB Commands
on the official Laravel blog.
Call Schema Methods
You can list the fields in a collection by calling the Schema::getColumns()
schema builder method in your application.
You can also use the following methods to return more information about the collection fields:
Schema::hasColumn(string $<collection>, string $<field name>)
: checks if the specified field exists in at least one documentSchema::hasColumns(string $<collection>, string[] $<field names>)
: checks if each specified field exists in at least one document
MongoDB is a schemaless database, so the preceding methods query the collection
data rather than the database schema. If the specified collection doesn't exist
or is empty, these methods return a value of false
.
Note
id Alias
Starting in Laravel MongoDB v5.1, the getColumns()
method represents
the _id
field name in a MongoDB collection as the alias id
in
the returned list of field names. You can pass either _id
or
id
to the hasColumn()
and hasColumns()
methods.
Example
The following example passes a collection name to the Schema::getColumns()
method to retrieve each field in the flowers
collection:
$fields = Schema::getColumns('flowers');
Create and Drop Collections
To learn how to create and drop collections, see the Perform Laravel Migrations section in the Schema Builder guide.