MongoDB
 sql >> Database >  >> NoSQL >> MongoDB

Ottieni documenti con tag nell'elenco, ordinati per numero totale di corrispondenze

Come ho risposto in In MongoDB, cerca in un array e ordina per numero di corrispondenze

È possibile utilizzare il Framework di aggregazione.

Ipotesi

  • tags l'attributo è un insieme (nessun elemento ripetuto)

Interroga

Questo approccio ti costringe a srotolare i risultati e rivalutare il predicato di corrispondenza con risultati non svolti, quindi è davvero inefficiente.

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

Risultati previsti

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