martedì 13 aprile 2021

MongoDb testare uguaglianza di 2 campi sulla stessa collection dati

Per eseguire una comparazione tra 2 campi stessa collection occorre usare una aggregation con una project.


Esempio


 


/* 1 */
{
    "_id" : ObjectId("5fae54de75f12730010c3d0c"),
    "first_name" : "MArio",
    "address" : {
        "state" : "ITALIA",
        "city" : "ROMA"
    },
    "nome" : "MArio",
    "ssn" : 12.0
}

/* 2 */
{
    "_id" : ObjectId("5fae550c75f12730010c3d0d"),
    "first_name" : "GINO",
    "address" : {
        "state" : "ITALIA",
        "city" : "MILANO"
    },
    "nome" : "PINO",
    "ssn" : 13.0
}


Se vogliamo tirar fuori solo i record con campo first_name uguale a nome dobbiamo fare in questo modo:

db.people.aggregate([{
    $project : {
        "CONDITION" : {
            $eq : ["$first_name", "$nome"] 
        },
        "document" : "$$ROOT"   
    }
}, {
    $match : {
        "CONDITION":true
    }
}]);

Nessun commento:

Posta un commento