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

Interroga l'array MongoDB e ordina con gli elementi più corrispondenti

Puoi farlo con il framework di aggregazione, anche se non è facile. Il problema sta nel fatto che non c'è un $in operatore come parte del framework di aggregazione. Quindi devi abbinare in modo programmatico ciascuno degli elementi nell'array, il che diventa molto disordinato. modifica :riordinato in modo che la corrispondenza sia prima, nel caso in cui $in ti aiuta a filtrare una buona parte.

db.test.aggregate(
  {$match:{"array.1":{$in:[100, 140,80]}}}, // filter to the ones that match
  {$unwind:"$array.1"}, // unwinds the array so we can match the items individually
  {$group: { // groups the array back, but adds a count for the number of matches
    _id:"$_id", 
    matches:{
      $sum:{
        $cond:[
          {$eq:["$array.1", 100]}, 
          1, 
          {$cond:[
            {$eq:["$array.1", 140]}, 
            1, 
            {$cond:[
              {$eq:["$array.1", 80]}, 
              1, 
              0
              ]
            }
            ]
          }
          ]
        }
      }, 
    item:{$first:"$array.item"}, 
    "1":{$push:"$array.1"}
    }
  }, 
  {$sort:{matches:-1}}, // sorts by the number of matches descending
  {$project:{matches:1, array:{item:"$item", 1:"$1"}}} // rebuilds the original structure
);

uscite:

{
"result" : [
    {
        "_id" : ObjectId("50614c02162d92b4fbfa4448"),
        "matches" : 2,
        "array" : {
            "item" : 3,
            "1" : [
                100,
                90,
                140
            ]
        }
    },
    {
        "_id" : ObjectId("50614bb2162d92b4fbfa4446"),
        "matches" : 1,
        "array" : {
            "item" : 1,
            "1" : [
                100,
                130,
                255
            ]
        }
    }
],
"ok" : 1
}

Puoi lasciare le matches campo fuori dal risultato se lo lasci fuori dal $project alla fine.