Database Reference
In-Depth Information
{
'$push'
: {
'comments'
:
comment
},
'$inc'
: {
'comments_shown'
:
1
} },
upsert
=
True
,
multi
=
True
)
db
.
social
.
news
.
update
(
{
'posts.id'
:
_id
},
{
'$push'
: {
'comments'
:
comment
},
'$inc'
: {
'comments_shown'
:
1
} },
upsert
=
True
,
multi
=
True
)
The preceding code can actually result in an unbounded number of comments being inserted
into the
social.wall
and
social.news
collections. To compensate for this, we need to peri-
odically run the following update statement to truncate the number of displayed comments
and keep the size of the news and wall documents manageable:
COMMENTS_SHOWN
=
3
def
def
truncate_extra_comments
():
db
.
social
.
news
.
update
(
{
'posts.comments_shown'
: {
'$gt'
:
COMMENTS_SHOWN
} },
{
'$pop'
: {
'posts.$.comments'
:
-
1
},
'$inc'
: {
'posts.$.comments_shown'
:
-
1
} },
multi
=
True
)
db
.
social
.
wall
.
update
(
{
'posts.comments_shown'
: {
'$gt'
:
COMMENTS_SHOWN
} },
{
'$pop'
: {
'posts.$.comments'
:
-
1
},
'$inc'
: {
'posts.$.comments_shown'
:
-
1
} },
multi
=
True
)
In order to efficiently execute the updates to the
social.news
and
social.wall
collections
just shown, we need to be able to quickly locate both of the following document types:
▪ Documents containing a given post
▪ Documents containing posts displaying too many comments
To quickly execute these updates, then, we need to create the following indexes:
>>>
>>>
for
for
collection
iin (
db
.
social
.
news
,
db
.
social
.
wall
):
...
collection
.
ensure_index
(
'posts.id'
)
...
collection
.
ensure_index
(
'posts.comments_shown'
)