Query documents by text into populted fields

Dear all,
suppose we have books collection like this
_id: “54353445kjh4j5h34j5h4”
name: “IT”,
pages: “1200”,
author: “648b162444af170e04de1020”
_id: “234544jke908897sd787s”
name: “Congo”,
pages: “1000”,
author: “985urue3423osi2334ii”

And Author collection like this
_id: “648b162444af170e04de1020”,
name: “Stephen King”,
_id: “985urue3423osi2334ii”,
name: "Michael Crichton

I need to filter and show only Stephen King’s books
How can i do this?


You can use a $lookup to get the author of a book and then $match on that:

/Edit to add that if this is a common query then you may want to think about embedding the author name in the books, after all how often does an author of a book change…

1 Like

I forgot to specify i’m working on Nodejs + Express
$lookup and $match seem not working

I’ve tryed tu use match inside .populate but i retrive even all books at least only field author populated with Stephen King and blank on other books

path: ‘author’,
match : {
name: 'Stephen King ,

I assume Mongoose is also in your stack given the fragment, I don’t have much experience with Mongoose and use the raw driver instead so won’t be able to help with that.
You could share the source files so someone who does know can take a look.

Ok tnx, i will close this topic and create a new one with the real case and some print screens
Thank you

After 3 days lost on web without success I found it
I must only define a $lookup for a join than a $set to extract the filed i need for queries.
That’s all

                              from: "roles",
                              localField: "role_id",
                              foreignField: "_id",
                              as: "role_obj",
                              pipeline: [
                                  $project: {
                              role_name: { $arrayElemAt: [ "$role_obj.name", 0 ] }

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.