Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create test data in MongoDB

Tags:

java

mongodb

I want to generate test data for MongoDB. The size should be 200 Mb. I tried this code:

@Test
    public void testMongoDBTestDataGenerate()
    {
        MongoClient mongoClient = new MongoClient("localhost", 27017);

        DB db = mongoClient.getDB("development");
        DBCollection collection = db.getCollection("ssv");

        for (int i = 0; i < 100; i++)
        {
            BasicDBObject document = new BasicDBObject();
            document.put("database", "test");
            document.put("table", "hosting");

            BasicDBObject documentDetail = new BasicDBObject();
            documentDetail.put("records", 99);
            documentDetail.put("index", "vps_index1");
            documentDetail.put("active", "true");

            document.put("detail", documentDetail);

            collection.insert(document);
        }

        mongoClient.close();

    }

How I can generate data exactly with this size?

like image 606
Peter Penzov Avatar asked Jul 01 '16 18:07

Peter Penzov


People also ask

How do I create a test database in MongoDB?

In MongoDB Compass, you create a database and add its first collection at the same time: Click "Create Database" to open the dialog. Enter the name of the database and its first collection. Click "Create Database"

What is test database in MongoDB?

If you are using Rational® Integration Tester V9. 5.0 or later, you can create MongoDB transports and run tests against them. MongoDB is an open source, document-oriented NoSQL database. MongoDB is different from traditional SQL-based relational databases.

How manually insert data in MongoDB?

To insert data into MongoDB collection, you need to use MongoDB's insert() or save() method.

How do I load sample data in MongoDB Atlas?

Load the sample dataset.Click the Ellipses (...) button for your cluster. Click Load Sample Dataset.


2 Answers

I am not getting what are you trying to achieve by setting size 200 Mb.

You can add logical checks.

  1. db.testCollection.stats() - You can check size of the collection before every insert.

  2. Object.bsonsize(..) - Also you can check document size before inserting to make it exactly 200 MB.

And also you can make capped collection where you can notify number of documents or size of collection.

Hope this helps.

like image 149
Somnath Muluk Avatar answered Nov 09 '22 22:11

Somnath Muluk


What I would probably do is create a capped collection with size 200MB (209715200 bytes):

db.createCollection( "ssv", { capped: true, size: 209715200 } )

Then insert records as you are doing. Then at intervals inside the for loop, check if the collection if full (or almost full).

So in your code, maybe (totally pseudo code):

if(i % 10 == 0) {
   if(db.ssv.stats().size >= 209715100){ //Or an arbitrary value closer to 200MB
     break;
   }
}
like image 40
airudah Avatar answered Nov 10 '22 00:11

airudah