您可以使用聚合框架来做到这一点,尽管这并不容易。$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
);
输出:
{
"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
}
如果您将matches
字段排除在最后,则可以将其排除在结果之外$project
。