You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

pymongo如何实现按位置顺序匹配的数组交集得分查询

MongoDB按位置对齐匹配得分查询实现方案

核心思路

利用MongoDB的数组遍历算子,逐个对比hash字段和输入数组相同索引位置的元素,相等则计1分,最终累加所有位置的得分即为匹配度。

具体实现代码

兼容MongoDB 3.2及以上版本,逻辑如下:

arr = [1, 2, 3]
collection.aggregate([{
    "$addFields": {
        "input_arr": arr, # 先将输入数组存入临时字段
        "weight": {
            "$sum": {
                "$map": {
                    "input": { "$range": [ 0, { "$size": "$hash" } ] },
                    "as": "idx",
                    "in": {
                        "$cond": [
                            { "$eq": [ 
                                # 分别取两个数组相同索引的元素对比
                                { "$arrayElemAt": [ "$hash", "$$idx" ] }, 
                                { "$arrayElemAt": [ "$input_arr", "$$idx" ] } 
                            ] },
                            1, # 匹配得1分
                            0  # 不匹配得0分
                        ]
                    }
                }
            }
        }
    }
},
{ "$sort": { "weight": -1 } }, # 按得分倒序排序
{ "$project": { "input_arr": 0 } } # 移除临时字段,不影响返回结果
])

逻辑验证

以你给出的示例文档和输入数组[1,2,3]为例:

  • 第一个文档{"hash": [1,2,7]}:索引0匹配得1分、索引1匹配得1分、索引2不匹配得0分,总得分2
  • 第二个文档{"hash": [3,2,1]}:索引0不匹配得0分、索引1匹配得1分、索引2不匹配得0分,总得分1
    排序后会优先返回第一个文档,完全符合需求。

可选简化写法(MongoDB 5.2+支持)

如果你的MongoDB版本高于等于5.2,可以用$zip算子简化配对逻辑,不需要手动遍历索引:

arr = [1, 2, 3]
collection.aggregate([{
    "$addFields": {
        "weight": {
            "$sum": {
                "$map": {
                    "input": { "$zip": { "inputs": [ "$hash", arr ] } },
                    "as": "pair",
                    "in": { "$cond": [ { "$eq": [ { "$first": "$$pair" }, { "$last": "$$pair" } ] }, 1, 0 ] }
                }
            }
        }
    }
},
{ "$sort": { "weight": -1 } }])

内容的提问来源于stack exchange,提问作者Some Guy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 00:45:05