Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

228
Vistas
Incrementing a "PlayerID" with a MongoDB Atlas Trigger

I need to have a playerID that is separate from _id and increments with each new entry into my users collection. I have tried to follow this tutorial with no luck. My counter collection is called playerIDCounter and my users collection is simply called users. I want each user document to have a playerID field that increments from 1 onwards.

This is my attempt at adapting the tutorial code for my own purpose:

exports = async function(changeEvent) {
const playerID = changeEvent.fullDocument.playerID;

const playerIDCounter = context.services.get("Cluster0").db(changeEvent.ns.db).collection("playerIDCounter");
const users = context.services.get("Cluster0").db(changeEvent.ns.db).collection(changeEvent.ns.coll);

(db.collection)
const counter = await playerIDCounter.findOneAndUpdate({playerID: changeEvent.ns },{$inc: { seq_value: 1 }}, { returnNewDocument: true, upsert : true});

const doc = {};

doc[`${changeEvent.ns.coll}.playerID`] = counter.seq_value;

const updateRes = await users.updateOne({playerID: playerID},{ $set: doc});

console.log(`Updated ${JSON.stringify(changeEvent.ns)} with counter ${counter.seq_value} result: ${JSON.stringify(updateRes)}`);

}

I also don't know whether or not I already need to have a playerID field in the document before it gets passed to this function. If the playerID field doesn't already exists will it be created and updated automatically? If not, then what placeholder value should playerID have?

I appreciate anyone who takes the time to help me. I have been stuck for a few days and there aren't too many posts on how to increment values in MongoDB.

Edit: I also don't understand the whole doc[`${changeEvent.ns.coll}.playerID`] = counter.seq_value bit - what's going on here?

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda