【问题标题】:How to find almost similar records in mongodb?如何在mongodb中找到几乎相似的记录?
【发布时间】:2018-01-11 09:48:00
【问题描述】:

这是搜索记录:

A = {
    field1: value1,
    field2: value2,
    ...
    fieldN: valueN
}

我在数据库中有很多这样的记录。

如果这些记录中的 N-M 个字段相等,则其他记录 (B) 几乎与记录 A 匹配。这是示例,M=2:

B = {
    field1: OTHER_value1,
    field2: OTHER_value2,
    field3: value3,
    ...
    fieldN: valueN
}

它可以是任何字段,而不仅仅是第一个。

P.S.:我已经为 postgresql - How to find almost similar records in sql? 复制了相同的查询,现在我想用 mongodb 执行此操作。

【问题讨论】:

    标签: mongodb algorithm similarity


    【解决方案1】:

    我的解决方案:

    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}}}
       ]
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-25
      • 1970-01-01
      • 1970-01-01
      • 2015-10-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多