Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

206
Visualizações
How to update multiple objects in array in a single mongodb document using mongoose

I know that this can be a repeat question but none of the existing answers solved my problem.

I have a friendsSchema like below:

const friendsSchema = new mongoose.Schema({
    owner: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Player'
    },
    friends: [{
        friendId: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Player'
        },
        isFromFacebook: {
            type: Boolean,
            default: false
        },
        thisFriendReceivedGiftTimeStamp: {
            type: Date,
            default: null
        },
        thisFriendSentGiftTimeStamp: {
            type: Date,
            default: null
        }
    }]
}, {
    timestamps: true
});

The client is sending me an array of friendsIds.

So, I want to find all objects in friends array which matches all friendsIds and update their thisFriendReceivedGiftTimeStamp to Date.now().

Consider the client is sending 100s of ids in friendsIds array, what will be the most efficient way to achieve the result.

Thanks in advance.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

db.collection.update({IF YOU WANT TO ADD QUERY ACCORDING TO OWNER FIELD PLEASE ADD HERE},
{
  "$set": {
    "friends.$[x].thisFriendReceivedGiftTimeStamp": new Date()
  }
},
{
  "arrayFilters": [
    {
      "x.friendId": {
        $in: [
          1,
          3,
          5
        ]
      }
    }
  ],
  "multi": true
})

arrayFilters should work great here. But I am not 100% sure about efficiency

Here is a working mongoplayground link

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda