在 MongoDB 中搜索数组并按匹配数排序 [英] In MongoDB search in an array and sort by number of matches
本文介绍了在 MongoDB 中搜索数组并按匹配数排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问题是下一个:
但是他们说使用聚合框架是可能的,这可能吗?
But they say that is possible using Aggregation Framework, it's possible?
推荐答案
是的,可以使用聚合框架.
Yes, it's possible using Aggregation Framework.
假设
- 此处使用的数据集与 获取列表中带有标签的文档,按匹配总数排序
tags
属性是一个集合(没有重复的元素)
- 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屋!
查看全文