MongoDB
 sql >> Base de Dados >  >> NoSQL >> MongoDB

Atualize Many se existir, caso contrário, crie para cada LeadId que não exista um novo Documento


Da sua consulta, já que você está fazendo .updateMany() , você não precisa fazer { multi: true } . De qualquer forma, geralmente você pode fazer upsert usando {upset: true} , mas idealmente criaria um novo documento com base em critérios de filtro com campos de atualização da consulta de entrada somente se nenhuma correspondência for encontrada no banco de dados. Mas já que aqui temos uma lista ($in ) nos critérios de filtro pode não funcionar normalmente, tente isto:
let winnerLeads = [1, 2, 3, 31, 5]
let groupTarget = 1
let howManyClaims = 2
let bulkArr = []
for (i of winnerLeads) {
    bulkArr.push({
        updateOne: {
            "filter": {
                LeadId: i,
                TargetedToBeClaimedByClientType: groupTarget
            },
            // If you wanted it to be incremented rather than replace the field, then try `$inc` instead of `$set`.
            "update": { $set: { TotalClaimsToBeClaimedByClientType: howManyClaims } },
            "upsert": true
        }
    })
}
db.EightWeekGamePlan.bulkWrite(bulkArr);

Dados de coleta:
/* 1 */
{
    "_id" : ObjectId("5e06eb8f400289966e00fac2"),
    "LeadId" : 1,
    "TotalClaimsToBeClaimedByClientType" : 1.0,
    "TargetedToBeClaimedByClientType" : 1
}

/* 2 */
{
    "_id" : ObjectId("5e06eb98400289966e00fb88"),
    "LeadId" : 2,
    "TotalClaimsToBeClaimedByClientType" : 1.0,
    "TargetedToBeClaimedByClientType" : 1
}

/* 3 */
{
    "_id" : ObjectId("5e06eba0400289966e00fc47"),
    "LeadId" : 3,
    "TotalClaimsToBeClaimedByClientType" : 0,
    "TargetedToBeClaimedByClientType" : 11
}

/* 4 */
{
    "_id" : ObjectId("5e06ebac400289966e00fd4b"),
    "LeadId" : 4,
    "TotalClaimsToBeClaimedByClientType" : 1,
    "TargetedToBeClaimedByClientType" : 11
}

/* 5 */
{
    "_id" : ObjectId("5e06ecef400289966e01273a"),
    "LeadId" : 5,
    "TotalClaimsToBeClaimedByClientType" : 1.0,
    "TargetedToBeClaimedByClientType" : 1
}

Resultado:
/* 1 */
{
    "_id" : ObjectId("5e06eb8f400289966e00fac2"),
    "LeadId" : 1,
    "TotalClaimsToBeClaimedByClientType" : 2.0,
    "TargetedToBeClaimedByClientType" : 1
}

/* 2 */
{
    "_id" : ObjectId("5e06eb98400289966e00fb88"),
    "LeadId" : 2,
    "TotalClaimsToBeClaimedByClientType" : 2.0,
    "TargetedToBeClaimedByClientType" : 1
}

/* 3 */
{
    "_id" : ObjectId("5e06eba0400289966e00fc47"),
    "LeadId" : 3,
    "TotalClaimsToBeClaimedByClientType" : 0,
    "TargetedToBeClaimedByClientType" : 11
}

/* 4 */
{
    "_id" : ObjectId("5e06ebac400289966e00fd4b"),
    "LeadId" : 4,
    "TotalClaimsToBeClaimedByClientType" : 1,
    "TargetedToBeClaimedByClientType" : 11
}

/* 5 */
{
    "_id" : ObjectId("5e06ecef400289966e01273a"),
    "LeadId" : 5,
    "TotalClaimsToBeClaimedByClientType" : 2,
    "TargetedToBeClaimedByClientType" : 1
}

/* 6 */
{
    "_id" : ObjectId("5e071eb1400289966e0597a0"),
    "TargetedToBeClaimedByClientType" : 1.0,
    "LeadId" : 3.0,
    "TotalClaimsToBeClaimedByClientType" : 2.0
}

/* 7 */
{
    "_id" : ObjectId("5e071e62400289966e059168"),
    "TargetedToBeClaimedByClientType" : 1.0,
    "LeadId" : 31.0,
    "TotalClaimsToBeClaimedByClientType" : 2.0
}

Basicamente, o bulkWrite não retorna nenhum documento, exceto o resultado da gravação, você pode verificar no banco de dados o resultado da operação de atualização, também do resultado acima 6 foi inserido como LeadId : 3 + TargetedToBeClaimedByClientType" : 1.0 (Então LeadId:3 está duplicado) combinação não está presente em DB &7 foi inserido como LeadId : 31 não está presente no banco de dados, restante 1 ,2 ,5 's TotalClaimsToBeClaimedByClientType foi atualizado.

Referência: bulkWrite