Database Reference
In-Depth Information
Relational databases typically support migrations via the
ALTER TABLE
statement, which al-
lows the developer to add or remove columns from a table. For instance, suppose we wanted
tion would be similar to the following:
ALTER
ALTER TABLE
TABLE
nodes
ADD
ADD COLUMN
COLUMN
short_description
varchar
(
255
);
The main drawbacks to the
ALTER TABLE
statement is that it can be time consuming to run on
a table with a large number of rows, and may require that your application experience some
downtimewhilethemigration executes, sincethe
ALTER TABLE
statement needstoholdalock
that your application requires to execute.
In MongoDB, we have the option of doing something similar by updating all documents in a
collection to reflect a new field:
db
.
nodes
.
update
(
{},
{
$set
:
{
short_description
:
''
} },
false
false
,
// upsert
true
true
// multi
);
This approach, however, has the same drawbacks as an
ALTER TABLE
statement: it can be
slow, and it can impact the performance of your application negatively.
Another option for MongoDB users is to update your application to account for the absence
of the new field. In Python, we might write the following code to handle retrieving both “old
style” documents (without a
short_description
field) as well as “new style” documents
(with a
short_description
field):
def
def
get_node_by_url
(
url
):
node
=
db
.
nodes
.
find_one
({
'url'
:
url
})
node
.
setdefault
(
'short_description'
,
''
)
return
return
node