您的解决方案确实应该是特定于 MongoDB 的,否则您最终会在客户端进行计算和可能的匹配,这对性能没有好处。
当然,您真正想要的是一种在服务器端进行处理的方法:
db.products.aggregate([
// Match the documents that meet your conditions
{ "$match": {
"$or": [
{
"features": {
"$elemMatch": {
"key": "Screen Format",
"value": "16:9"
}
}
},
{
"features": {
"$elemMatch": {
"key" : "Weight in kg",
"value" : { "$gt": "5", "$lt": "8" }
}
}
},
]
}},
// Keep the document and a copy of the features array
{ "$project": {
"_id": {
"_id": "$_id",
"product_id": "$product_id",
"ean": "$ean",
"brand": "$brand",
"model": "$model",
"features": "$features"
},
"features": 1
}},
// Unwind the array
{ "$unwind": "$features" },
// Find the actual elements that match the conditions
{ "$match": {
"$or": [
{
"features.key": "Screen Format",
"features.value": "16:9"
},
{
"features.key" : "Weight in kg",
"features.value" : { "$gt": "5", "$lt": "8" }
},
]
}},
// Count those matched elements
{ "$group": {
"_id": "$_id",
"count": { "$sum": 1 }
}},
// Restore the document and divide the mated elements by the
// number of elements in the "or" condition
{ "$project": {
"_id": "$_id._id",
"product_id": "$_id.product_id",
"ean": "$_id.ean",
"brand": "$_id.brand",
"model": "$_id.model",
"features": "$_id.features",
"matched": { "$divide": [ "$count", 2 ] }
}},
// Sort by the matched percentage
{ "$sort": { "matched": -1 } }
])
既然您知道所应用的 $or 条件的“长度”,那么您只需找出“特征”数组中有多少元素符合这些条件。这就是管道中的第二个 $match 的全部内容。
一旦你有了这个计数,你只需将条件数除以作为 $or 传入的条件数。这里的美妙之处在于,现在您可以用这种方式做一些有用的事情,比如按相关性排序,然后甚至“分页”结果服务器端。
当然,如果您想要对此进行一些额外的“分类”,您需要做的就是在管道的末尾添加另一个 $project 阶段:
{ "$project": {
"product_id": 1
"ean": 1
"brand": 1
"model": 1,
"features": 1,
"matched": 1,
"category": { "$cond": [
{ "$eq": [ "$matched", 1 ] },
"100",
{ "$cond": [
{ "$gte": [ "$matched", .7 ] },
"70-99",
{ "$cond": [
"$gte": [ "$matched", .4 ] },
"40-69",
"under 40"
]}
]}
]}
}}
或类似的东西。但是$cond 运算符可以在这里为您提供帮助。
架构应该没问题,因为您可以在特征数组中的条目的“键”和“值”上建立一个复合索引,这应该可以很好地扩展查询。
当然,如果您确实需要更多的东西,例如分面搜索和结果,您可以查看 Solr 或弹性搜索等解决方案。但是这里的完整实现会有点冗长。