Esistono diversi approcci; la scelta dipende dalla versione di MongoDB. Riporto le risposte della shell: il contenuto è di base una rappresentazione JSON, facile da tradurre nelle entità DBObject in Java o in JavaScript da eseguire sul server.
MongoDB 2.6 e successivi: le operazioni sugli insiemi
Il primo approccio, il più rapido, sfrutta le nuove operazioni insiemistiche:
var test = [ "t3", "t4", "t5" ]; db.collection.aggregate([ { "$match": { "tags": {"$in": test } }}, { "$project": { "tagMatch": { "$setIntersection": [ "$tags", test ] }, "sizeMatch": { "$size": { "$setIntersection": [ "$tags", test ] } } }}, { "$match": { "sizeMatch": { "$gte": 1 } } }, { "$project": { "tagMatch": 1 } } ])
Gli operatori nuovi sono $setIntersection, che fa il lavoro principale, e $size, che misura la dimensione dell'array e consente il filtraggio successivo. In sostanza si tratta di un confronto tra insiemi per individuare gli elementi in comune.
Versioni precedenti di MongoDB
È comunque possibile, con qualche stage in più e possibili ripercussioni sulle prestazioni se gli array sono grandi:
var test = [ "t3", "t4", "t5" ]; db.collection.aggregate([ { "$match": { "tags": {"$in": test } }}, { "$project": { "tags": 1, "match": { "$const": test } }}, { "$unwind": "$tags" }, { "$unwind": "$match" }, { "$project": { "tags": 1, "matched": { "$eq": [ "$tags", "$match" ] } }}, { "$match": { "matched": true }}, { "$group": { "_id": "$_id", "tagMatch": { "$push": "$tags" }, "count": { "$sum": 1 } }} { "$match": { "count": { "$gte": 1 } }}, { "$project": { "tagMatch": 1 }} ])
Se tutto questo risulta troppo macchinoso o gli array sono abbastanza grandi da incidere sulle prestazioni, resta sempre mapReduce:
var test = [ "t3", "t4", "t5" ]; db.collection.mapReduce( function () { var intersection = this.tags.filter(function(x){ return ( test.indexOf( x ) != -1 ); }); if ( intersection.length > 0 ) emit ( this._id, intersection ); }, function(){}, { "query": { "tags": { "$in": test } }, "scope": { "test": test }, "output": { "inline": 1 } } )
In tutti i casi l'operatore $in aiuta a ridurre i risultati, pur non essendo il match completo; l'altro elemento comune è il controllo della "dimensione" dell'intersezione per limitare la risposta.
Tutto piuttosto semplice da scrivere: se non sei già su MongoDB 2.6 o successivi, conviene aggiornare per ottenere le prestazioni migliori.