mongodb - Efficient way to insert documents n times in a loop

Viewed 19

What is a good method to insert multiple documents into mongodb?

I have to perform two inserts (into 2 collections) - "n" times.

Currently, I accomplish it with a while loop but it seems like a lot of requests to the database.

handler.post(async (req, res) => { 
while (potentialMatchCount < 10) {
potentialMatchCount+=1;
const email = gender=="0"?"m":"f" + potentialMatchCount + "@wedpicker.com" 
const matchId = nanoid(10);  

    await req.db
      .collection('users')
      .insertOne({
        _id: matchId,
        email,
    });
      await req.db.collection('userLocations').insertOne(
        {
        "_id": matchId,
        },
        {
          $set: {
            type : "Point",
            coordinates : matchLocation,
            updated: new Date(),
          },
        }
      );
  }
1 Answers

i'd say not to worry about it until it shows up as a problem. There is a bulk interface, which you can use, but there really isn't a need for this optimization until you are hitting a performance issue. see the bulk documentation here https://www.mongodb.com/docs/manual/reference/method/Bulk/

Related