Ticket: Get Comments. What is difference?(failed unit test. but I got validation code, anyway )

I checked late for the hint(sort by comments date while lookup) of the problem and solved it by unwind by comments, then sorting, then group by _id with push comments.

I got validation code but unit test fails as belows.

  client = <FlaskClient <Flask 'mflix.factory'>>

@pytest.mark.get_comments
def test_comments_should_be_sorted_by_date(client):
    # in order from most to least recent
    movie_ids = [
        "573a1391f29313caabcd8414",
        "573a1392f29313caabcd9d4f",
        "573a1392f29313caabcdae3d",
        "573a1392f29313caabcdb40b",
        "573a1392f29313caabcdb585",
        "573a1393f29313caabcdbe7c",
        "573a1393f29313caabcdd6aa"
    ]
    for id in movie_ids:
>           comments = get_movie(id).get('comments', [])
E           AttributeError: 'NoneType' object has no attribute 'get'
tests/test_get_comments.py:41: AttributeError

I don’t know the difference between lookup in pymongo and mongodb’s aggregation operator.

Below is my pipeline code.

    pipeline = [
        {"$match": {"_id": ObjectId(id)}},
        {'$lookup': {'from': 'comments', 'localField': '_id', 'foreignField': 'movie_id', 'as': 'comments'}},
        {'$unwind': '$comments'},
        {'$sort': {'comments.date': -1}},
        {'$group': {'_id': '$_id', 'comments': {'$push': '$comments'}}},
    ]

Hi @ys_70859,

You need to check the code and try to use sort in lookup pipeline only, otherwise the results might differ.

This link may help:

https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/index.html#join-conditions-and-uncorrelated-sub-queries

Kanika