Database Reference
In-Depth Information
Log an event
Logging an event such as a page request (i.e., “hit”) is the main “write” activity for your sys-
tem. To maximize performance, you'll be doing in-place updates with the
upsert=True
to
create documents if they haven't been created yet. Consider the following example:
from
from
datetime
datetime
import
import
datetime
,
time
def
def
log_hit
(
db
,
dt_utc
,
site
,
page
):
# Update daily stats doc
id_daily
=
dt_utc
.
strftime
(
'%Y%m
%d
/'
)
+
site
+
page
hour
=
dt_utc
.
hour
minute
=
dt_utc
.
minute
# Get a datetime that only includes date info
d
=
datetime
.
combine
(
dt_utc
.
date
(),
time
.
min
)
query
=
{
'_id'
:
id_daily
,
'metadata'
: {
'date'
:
d
,
'site'
:
site
,
'page'
:
page
} }
update
=
{
'$inc'
: {
'hourly.
%d
'
%
(
hour
,):
1
,
'minute.
%d
.
%d
'
%
(
hour
,
minute
):
1
} }
db
.
stats
.
daily
.
update
(
query
,
update
,
upsert
=
True
)
# Update monthly stats document
id_monthly
=
dt_utc
.
strftime
(
'%Y%m/'
)
+
site
+
page
day_of_month
=
dt_utc
.
day
query
=
{
'_id'
:
id_monthly
,
'metadata'
: {
'date'
:
d
.
replace
(
day
=
1
),
'site'
:
site
,
'page'
:
page
} }
update
=
{
'$inc'
: {
'daily.
%d
'
%
day_of_month
:
1
} }
db
.
stats
.
monthly
.
update
(
query
,
update
,
upsert
=
True
)
The upsert operation (i.e.,
upsert=True
) performs an update if the document exists, and an
insert if the document does not exist.