在MongoDB中搜索数组并按匹配数排序 [英] In MongoDB search in an array and sort by number of matches
本文介绍了在MongoDB中搜索数组并按匹配数排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问题是下一个:
但是他们说使用Aggregation Framework可以实现,有可能吗?
But they say that is possible using Aggregation Framework, it's possible?
推荐答案
是的,可以使用Aggregation Framework.
Yes, it's possible using Aggregation Framework.
假设
- The dataset used here is the same used in Get documents with tags in list, ordered by total number of matches
tags
attribute is a set (no repeated elements)
查询
这种方法迫使您取消结果,并用未结束的结果重新评估匹配谓词,因此它的效率很低.
This approach forces you to unwind the results and reevaluate the match predicate with unwinded results, so its really inefficient.
db.test_col.aggregate(
{$match: {tags: {$in: ["shirt","cotton","black"]}}},
{$unwind: "$tags"},
{$match: {tags: {$in: ["shirt","cotton","black"]}}},
{$group: {
_id:{"_id":1},
matches:{$sum:1}
}},
{$sort:{matches:-1}}
);
预期结果
{
"result" : [
{
"_id" : {
"_id" : ObjectId("5051f1786a64bd2c54918b26")
},
"matches" : 3
},
{
"_id" : {
"_id" : ObjectId("5051f1726a64bd2c54918b24")
},
"matches" : 2
},
{
"_id" : {
"_id" : ObjectId("5051f1756a64bd2c54918b25")
},
"matches" : 1
}
],
"ok" : 1
}
这篇关于在MongoDB中搜索数组并按匹配数排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文