How to use set(data structure) in mongodb console?

1.3k views Asked by At

As I understand, the mongodb console has an integrated javascript interpreter so my question is why this code does not work if its a valid javascript:

//db = connect("localhost:27017/tecnicas")

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

diaFavorito = ["lunes", "martes", "miercoles", "sabado"]
sexo = ["hombre", "mujer"];
heladoFavorito = ["vainilla", "chocolate", "fresa", "coco"]

for(i = 0; i < 20; i++){
    print(db.usuarios.insert({
        fday: diaFavorito[getRandomInt(0, diaFavorito.length-1)],
        genero: sexo[getRandomInt(0, sexo.length-1)],
        fice: heladoFavorito[getRandomInt(0, heladoFavorito.length-1)],
        indice: i+1,
        ingresos: getRandomInt(12000, 120000)
    }))
}

// SECOND PART

paises = ["Mexico", "USA", "Portugal", "Nepal", "Argelia", "Chile"]
for(i = 0; i < 20; i++){
    numeroDePaisesVisitados = getRandomInt(1,6)
    var misPaisesVisitados = new Set(); // THE ERROR OCCURS HERE
    while(misPaisesVisitados.size != numeroDePaisesVisitados){
        misPaisesVisitados.add(
            paises[getRandomInt(0,paises.length-1)]
        )
    }
    var miArregloDePaisesVisitados = Array.from(misPaisesVisitados)
    print(db.usuarios.update(
        {indice:i+1},
        {$set: {paisesVisitados: miArregloDePaisesVisitados}}
    ))
}

The error message is:

ReferenceError: Set is not defined

1

There are 1 answers

0
AudioBubble On BEST ANSWER

ECMAScript.

You can only used defined built in functions and Set() is not one of them. You just want a plain object and set it's keys like so:

var misPaisesVisitados = {};
while(misPaisesVisitados.size != numeroDePaisesVisitados){
  misPaisesVisitados[paises[getRandomInt(0,paises.length-1)]] = 1;
}
var miArregloDePaisesVisitados = Object.keys(misPaisesVisitados);

The Object will only have unique keys ( or a "set" ) and then you extract those unique key names from the Object.