简体   繁体   中英

Insert documents with random data in MongoDB

Goog morning.

I am trying to code some scripts to insert documents in a collection in MongoDB. The problem is that I need the data to be random. This is my code:

async function run(service) {
  try {
    await client.connect();
    const database = client.db("myDb");
    const collection = database.collection("myEvents");
    // create a filter to update all movies filtering the service
    const filter = { service: service };
    const updateDoc = {
        $set: {
          idIn: (Math.floor(Math.random() * 20) + 1) + 5, 
          idOut: Math.floor(Math.random() * 10) + 1
        },
    };

    const result = await collection.updateMany(filter, updateDoc);
  } finally {
    await client.close();
  }
}
let service = readline.question("Insert an id: ");
run(service).catch(console.dir); 

Here the data is created once and then updates all the documents in the collection with the same values. I need to update every document with two different (IdIn and IdOut) values.

Thanks in advance.

The problem here is how a random number is generated. If all numbers are based in the same seed, all will be the same.

So you haveto use forEach() to iterate over the collection and adding values, then, the seed is not the same for all values.

Note that forEach is not the same using mongoose and mongo . Using mongo you can do collection.find().forEach(...) .

Using mongoose is in this way:

model.find({}).then(doc => 
  doc.forEach(element => {
    element.idIn = (Math.floor(Math.random() * 20) + 1) + 5
    element.idOut = Math.floor(Math.random() * 10) + 1
    element.save()
  }))

The find query is empty because you want to update every document. With the values returned by the query (all documents), you can iterate one by one using forEach , and calculate a random number for each one and adding to value.
And after that save the document into collection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM