mongodbmongodb-querymongojs

How to insert my data into collection in a loop in mongoDB?


I want to populate data into a collection in mongo db. If I to hard-code the insert query, it would be as if:

db.devices.insertMany([
    {"_id" : "FX200FTQ2109BZ00", "cloud_blueprint_id" : 105969, "cloud_blueprint_name" : "AWS-BP" },
    {"_id" : "FX200FTQ2109BZ01", "cloud_blueprint_id" : 105969, "cloud_blueprint_name" : "AWS-BP" },
    {"_id" : "FX200FTQ2109BZ02", "cloud_blueprint_id" : 105969, "cloud_blueprint_name" : "AWS-BP" },
    ... 
    {"_id" : "FX200FTQ2109BZ0A", "cloud_blueprint_id" : 105969, "cloud_blueprint_name" : "AWS-BP" },
    ...
    {"_id" : "FX200FTQ2109BZ0Z", "cloud_blueprint_id" : 105969, "cloud_blueprint_name" : "AWS-BP" }
]);

As we can see, the last char of "_id" value is in the range of (0~9,A~Z). So is there a loop way I can have such data populated inside MongoDB Shell ?

Thanks,

Jack


Solution

  • Voila:

     mongos> var characters='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
     mongos>var length=characters.length;
     mongos>for(var i = 0; i < length; i++ ) {
      db.devices.insert({
        "_id":"FX200FTQ2109BZ0"+characters.charAt(Math.floor(i)) ,
        "cloud_blueprint_id": 105969 ,
        "cloud_blueprint_name":"AWS-BP" 
        } 
      )}
      WriteResult({ "nInserted" : 1 })
      mongos> db.devices.count()
      62
      mongos> db.devices.findOne()
     {
        "_id" : "FX200FTQ2109BZ0A",
        "cloud_blueprint_id" : 105969,
         "cloud_blueprint_name" : "AWS-BP"
     }
      mongos> 
    

    Explained:

    1. Define variable "characters" that contain the characters you need for the last character in your string _id
    2. Define another variable that will contain the lenght of the characters string
    3. Add the insert() request inside the for loop and generate the _id based on incremental loop variable converting it into character based on string character location.

    Afcourse you can modify and create bigger batches with multiple entries inside insertMany

    here is the insertMany option:

    mongos> var characters='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';var length=characters.length;var query=[],many="";for(var i = 0; i < length; i++ ) { query[i]='{"_id":"FX200FTQ2109BZ0'+characters.charAt(Math.floor(i))+'" ,"cloud_blueprint_id": 105969 ,"cloud_blueprint_name":"AWS-BP"  }';};many="["+query.join(",")+"]";print(many);db.x.insertMany(eval(many));