Get documents with tags in list, ordered by total number of matches

后端 未结 3 1458
梦谈多话
梦谈多话 2020-12-09 06:36

Given the following MongoDB collection of documents :

{
 title : \'shirt one\'
 tags : [
  \'shirt\',
  \'cotton\',
  \'t-shirt\',
  \'black\'
 ]
},
{
 title         


        
3条回答
  •  自闭症患者
    2020-12-09 07:05

    As i answered in In MongoDB search in an array and sort by number of matches

    It's possible using Aggregation Framework.

    Assumptions

    • tags attribute is a set (no repeated elements)

    Query

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

    Expected Results

    {
        "result" : [
            {
                "_id" : {
                    "_id" : ObjectId("5051f1786a64bd2c54918b26")
                },
                "matches" : 3
            },
            {
                "_id" : {
                    "_id" : ObjectId("5051f1726a64bd2c54918b24")
                },
                "matches" : 2
            },
            {
                "_id" : {
                    "_id" : ObjectId("5051f1756a64bd2c54918b25")
                },
                "matches" : 1
            }
        ],
        "ok" : 1
    }
    

提交回复
热议问题