Hello, I am struggling with a problem in my web application. I want to build a search query using the MongoDB Search Atlas. The goal is to search through one schema of our MongoDB database for matching values. That is easy with a simple search index, the problem is that I would like to also search inside nested documents of the original schema documents.
So for example with the search query, I want to find matching values in our Order schema fields which looks something like this:
Order Schema:
{
buyer: ObjectId(‘User_schema_Id’),
seller: ObjectId(‘User_schema_Id’),
listings: [
{
listing: ObjectId(‘Listing_schema_Id’),
listingPrice: 99,
…
}
{
listing: ObjectId(‘Listing_schema_Id’),
listingPrice: 99,
…
}
],
…
}
The User Schema (referenced in order.buyer and order.seller) looks something like this:
User Schema
{
email: ‘mike@gmail.com’,
firstName: ‘Mike’,
…
}
And the Listing Schema (referenced in order.listings.listing) looks something like this:
Listing Schema
{
title: ‘Blue Sofa’,
status: ‘Active’,
…
}
Now, if the search Query is something like ‘Couch’ or ‘Mike’ or ‘mike@gmail.com’, I would like to search inside the following Order fields for a matching value:
- Order.buyer.firstName
- Order.buyer.email
- Order.seller.firstName
- Order.seller.email
- Order.listings.listing.title (for each listing document in the order.listings array)
I also want to return the search array results with the buyer, seller and listing nested documents populated.
Is that even possible? I don’t know where to start from.
This is what I have so far, but it’s not leading me anywhere:
let orders = await Order.aggregate([
{
$search: {
index: 'ordersSearch',
embeddedDocument: {
path: 'seller',
operator: {
text: {
path: 'seller.email',
query: searchTerm,
},
},
},
},
},
{
$search: {
index: 'ordersSearch',
embeddedDocument: {
path: 'listings',
operator: {
text: {
path: 'listings.listing.title',
query: searchTerm,
},
},
},
},
},
…
]);