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
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:
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));