Chapter 2: Basic Aggregation - Utility Stages Lab: Using Cursor-like Stages- Cannot get the right result

Hi,

Following is my code. I am getting results but not the right one. Please guide:

db.movies.aggregate ([ { ‘$match’: { ‘countries’: ‘USA’ } },
{ ‘$match’: { ‘tomatoes.viewer.rating’: { ‘$gte’: 3 } } },
{ ‘$match’: { ‘cast’: { ‘$in’: [ ‘Sandra Bullock’, ‘Tom Hanks’, ‘Julia Roberts’, ‘Kevin Spacey’, ‘George Clooney’ ] } } },
{ ‘$project’: { ‘title’: 1, ‘cast’: 1, ‘tomato’: ‘$tomatoes.viewer.rating’ } },
{ ‘$addFields’: { ‘num_fav’: { ‘$size’: { ‘$setIntersection’: [ ‘$cast’, [ ‘Sandra Bullock’, ‘Tom Hanks’, ‘Julia Roberts’, ‘Kevin Spacey’, ‘George Clooney’ ] ] } } } },
{ ‘$sort’: { ‘num_fav’: -1 } },
{ ‘$sort’: { ‘tomato’: -1 } },
{ ‘$sort’: { ‘title’: -1 } },
{ ‘$skip’: 24 },
{’$limit’:1} ])

{ “_id” : ObjectId(“573a1399f29313caabcede4e”), “title” : “The Pelican Brief”, “cast” : [ “Julia Roberts”, “Denzel Washington”, “Sam Shepard”, “John Heard” ], “tomato” : 3.2, “num_fav” : 1 }

Hi @priyanka_prasad, welcome to the community.
Can you please combine all your sorts in a single stage?
Like this:

{ "$sort": { "num_fav": -1, "tomato": -1, "title": -1  } }

Hopefully, that will fix the issue.

In case you have any doubts, please feel free to reach out to us.

Thanks and Regards.
Sourabh Bagrecha,
Curriculum Services Engineer

I also encourage you to look at the $match documentation at https://docs.mongodb.com/manual/reference/operator/aggregation/match/.

Your 3 consecutive $match stages should be merged into a single one. I do not know if merging allows a better use of indexes but it might.

1 Like

@SourabhBagrecha Thank you! It is working now

1 Like