Database Reference
In-Depth Information
{
'_id'
:
node
[
'_id'
],
'num_comment_pages'
:
node
[
'num_comment_pages'
] },
{
'$inc'
: {
'num_comment_pages'
:
1
} })
db
.
comment_pages
.
update
(
{
'node_id'
:
node
[
'_id'
],
'page'
:
node
[
'num_comment_pages'
]
+
1
},
{
'$inc'
: {
'count'
:
1
},
'$push'
: {
'comments'
:
comment
} },
upsert
=
True
)
There are a few things to note about this code:
The first update will only
$push
a comment if the page is not yet full.
If
the last comment page
is
full, we need to increment the
num_comment_pages
propertyinthenode(solongassome otherprocess hasnotalready incremented that
property).
comment page. Here, we've dropped the
count
constraint to make sure the
$push
goes through. (While it's technically possible that 100 other concurrent writers were
adding comments and the new page is already full, it's highly unlikely, and the ap-
plication works just fine if there happen to be 101 comments on a page.)
Tosupportthe
update
operations,weneedtomaintainacompoundindexon
node_id,page
in the
comment_pages
collection:
>>>
>>>
db
.
comment_pages
.
ensure_index
([
...
...
(
'node_id'
,
1
), (
'page'
,
1
)])
Operation: View paginated comments
Thefollowingfunctiondefineshowtopaginatecommentswherethenumberofcommentson
a page is not known precisely (i.e., with
roughly
100 comments, as in this case):
def
def
find_comments
(
discussion_id
,
skip
,
limit
):
query
=
db
.
comment_pages
.
find
(
{
'node_id'
:
node_id
} )
query
=
query
.
sort
(
'page'
)
for
for
page
iin
query
: