我正在努力解决我的 Web 应用程序中的问题。我想使用 MongoDB 搜索图集构建搜索查询。目标是在我们的 MongoDB 数据库的一个模式中搜索匹配值。使用简单的搜索索引很容易,问题是我还想在原始模式文档的嵌套文档中搜索。 因此,例如对于搜索查询,我想在我们的订单模式字段中找到匹配值,看起来像这样:
订单模式:
{
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,
…
}
],
…
}
用户模式(在 order.buyer 和 order.seller 中引用)看起来像这样:
用户模式
{
email: ‘[email protected]’,
firstName: ‘Mike’,
…
}
Listing Schema(在 order.listings.listing 中引用)看起来像这样:
上市模式
{
title: ‘Blue Sofa’,
status: ‘Active’,
…
}
现在,如果搜索查询是“Couch”或“Mike”或“[email protected]”之类的东西,我想在以下订单字段中搜索匹配值:
我还想返回包含买家、卖家和列表嵌套文档的搜索数组结果。
这可能吗?我不知道从哪里开始。
这是我目前所拥有的,但它并没有带我去任何地方:
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,
},
},
},
},
},
…
]);