如何在mongodb中找到几乎相似的记录?
这是搜索记录:如何在mongodb中找到几乎相似的记录?,mongodb,algorithm,similarity,Mongodb,Algorithm,Similarity,这是搜索记录: A = { field1: value1, field2: value2, ... fieldN: valueN } 我在数据库里有很多这样的记录 如果这些记录中的N-M字段相等,则其他记录(B)几乎与记录A匹配。这是一个示例,M=2: B = { field1: OTHER_value1, field2: OTHER_value2, field3: value3, ... fieldN: valueN }
A = {
field1: value1,
field2: value2,
...
fieldN: valueN
}
我在数据库里有很多这样的记录
如果这些记录中的N-M字段相等,则其他记录(B)几乎与记录A匹配。这是一个示例,M=2:
B = {
field1: OTHER_value1,
field2: OTHER_value2,
field3: value3,
...
fieldN: valueN
}
它可以是任何字段,而不仅仅是第一个字段
注意:我已经为postgresql复制了相同的查询,现在我想用mongodb来实现这一点 我的解决方案:
db.col.aggregate(
[
{
$addFields:
{
nonMatchCount: 0
}
},
{
$addFields: {
nonMatchCount:
{
$cond: [{$eq: ['$field1', 'OTHER_value1']}, '$nonMatchCount', {$sum: ['$nonMatchCount', 1]}]
}
}
},
{
$addFields: {
nonMatchCount:
{
$cond: [{$eq: ['$field2', 'OTHER_value2']}, '$nonMatchCount', {$sum: ['$nonMatchCount', 1]}]
}
}
},
{
$addFields: {
nonMatchCount:
{
$cond: [{$eq: ['$field3', 'value3']}, '$nonMatchCount', {$sum: ['$nonMatchCount', 1]}]
}
}
},
...
{
$addFields: {
nonMatchCount:
{
$cond: [{$eq: ['$fieldN', 'valueN']}, '$nonMatchCount', {$sum: ['$nonMatchCount', 1]}]
}
}
},
{$match: { nonMatchCount: {$lte: 2}}}
]
);