1

Is it possible to use aggregate function after the find function in MongoDB? I want to query a document and then aggregate according to find result.

db.movies.find({"runtime":30},{runtime:1,year:1,"imdb.rating":1,"imdb.votes":1,type:1,"tomatoes.viewer.rating":1,"awards.wins":1}).limit(3).aggregate([{$group:{_id:"$runtime",award_wins:{$sum:1}}}])

After executing this command I am getting an error that, aggregate is not a function,

E QUERY [js] TypeError: db.movies.find(...).limit(...).aggregate is not a function :

3 Answers 3

1

Run it as below,you can't run aggregate along/after find

db.movies.aggregate([
{$match:{"runtime":30}},
{$project{runtime:1,year:1,"imdb.rating":1,"imdb.votes":1,type:1,"tomatoes.viewer.rating":1,"awards.wins":1}},
{$limit:3},
{$group:{_id:"$runtime",award_wins:{$sum:1}}}
])
Sign up to request clarification or add additional context in comments.

1 Comment

Do upvote and mark as answer if the answer was helpful.
1

To invoke the aggregate function, you must use db..aggregate instead of find. Try the below:

db.movies.aggregate({"runtime":30},{runtime:1,year:1,"imdb.rating":1,"imdb.votes":1,type:1,"tomatoes.viewer.rating":1,"awards.wins":1}).limit(3).aggregate([{$group:{_id:"$runtime",award_wins:{$sum:1}}}])

Comments

1

aggregate() cannot be used along with find(). You should use corresponding aggregate methods to execute the query.

Edit: Try this out.

db.movies.aggregate([
{$match:{"runtime":30}},
{$project:{runtime:1,year:1,"imdb.rating":1,"imdb.votes":1,type:1,"tomatoes.viewer.rating":1,"awards.wins":1}},
{$limit:3},
{$group:{_id:"$runtime",award_wins:{$sum:1}}}
])

1 Comment

Can you please explain a little more with an example?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.