查询MongoDB数组并使用最匹配的元素进行排序

Rez*_*eza 0 java mongodb

我需要你在以下情况下的专业知识.

我有一个这样的集合:

"array" : {
    "item" : 1,
    "1" : [100, 130, 255],
}

"array" : {
    "item" : 2,
    "1" " [0, 70, 120],
}

"array" : {
    "item" : 3,
    "1" : [100, 90, 140],

}
Run Code Online (Sandbox Code Playgroud)

我这样查询这个集合:

 db.test.find(array.1 : {$in : [100, 80, 140]});
Run Code Online (Sandbox Code Playgroud)

这将返回项目编号1和3,因为它将提供的数组中的任何值与集合中的值匹配.但是,我想对此数组进行排序,以便为我提供更相似数字的结果.结果应分别为第3项和第1项.

然而,我可以获取结果并使用k近邻算法对数组进行排序.然而,处理大型数据集会使这非常不受欢迎(或者是吗?)MongoDB中是否有任何函数可以提供此功能?我使用Java,任何算法都足够快地实现这个目标吗?任何帮助表示赞赏.

谢谢.

Eve*_*man 5

您可以使用聚合框架执行此操作,但这并不容易.麻烦在于没有$in运营商作为聚合框架的一部分.因此,您必须以编程方式匹配数组中的每个项目,这会非常混乱.编辑:重新排序,以便匹配是第一个,以防止$in您过滤好的部分.

db.test.aggregate(
  {$match:{"array.1":{$in:[100, 140,80]}}}, // filter to the ones that match
  {$unwind:"$array.1"}, // unwinds the array so we can match the items individually
  {$group: { // groups the array back, but adds a count for the number of matches
    _id:"$_id", 
    matches:{
      $sum:{
        $cond:[
          {$eq:["$array.1", 100]}, 
          1, 
          {$cond:[
            {$eq:["$array.1", 140]}, 
            1, 
            {$cond:[
              {$eq:["$array.1", 80]}, 
              1, 
              0
              ]
            }
            ]
          }
          ]
        }
      }, 
    item:{$first:"$array.item"}, 
    "1":{$push:"$array.1"}
    }
  }, 
  {$sort:{matches:-1}}, // sorts by the number of matches descending
  {$project:{matches:1, array:{item:"$item", 1:"$1"}}} // rebuilds the original structure
);
Run Code Online (Sandbox Code Playgroud)

输出:

{
"result" : [
    {
        "_id" : ObjectId("50614c02162d92b4fbfa4448"),
        "matches" : 2,
        "array" : {
            "item" : 3,
            "1" : [
                100,
                90,
                140
            ]
        }
    },
    {
        "_id" : ObjectId("50614bb2162d92b4fbfa4446"),
        "matches" : 1,
        "array" : {
            "item" : 1,
            "1" : [
                100,
                130,
                255
            ]
        }
    }
],
"ok" : 1
}
Run Code Online (Sandbox Code Playgroud)

如果将matches字段排除在最后,则可以将字段排除在结果之外$project.