Reputation: 121
case 3:
BasicDBObject []document= new BasicDBObject(); // error
DBCollection table1 = db.getCollection("user");
document[0].put("name", "mkyong");
document[0].put("age", 30);
table1.insert(document);
System.out.println("Collection Inserted successfully");
break;
Not understanding the problem with the initialization.
Upvotes: 0
Views: 196
Reputation: 437
you would get compile time error because the array initialization is not correct.
BasicDBObject []document= new BasicDBObject(); //error
Basic Array Initialization in java is as below
Object objectArr[] = new Object[10];
So you have to initialize the array and pass the values in below manner.
BasicDBObject []document1= new BasicDBObject[2];
document1[0] = new BasicDBObject();
document1[0].put("name", "mkyong12");
document1[0].put("age", 30);
document1[1] = new BasicDBObject();
document1[1].put("name", "test12");
document1[1].put("age", 44);
You have to make sure each array object should be initialized otherwise you fail with NullPointerException
Hope this helps.
Upvotes: 1
Reputation: 2330
You can use BasicDBList
:
BasicDBObject document = new BasicDBObject();
document.put("name", "mkyong");
document.put("age", 30);
BasicDBList documentList = new BasicDBList();
documentList.add(document);
DBCollection table1 = db.getCollection("user");
table1.insert(documentList.get(0));
System.out.println("Collection Inserted successfully");
Upvotes: 0
Reputation: 5095
insert
method takes a DBObject.
BasicDBObject document= new BasicDBObject();
document.put("name", "mkyong");
document.put("age", 30);
table1.insert(document);
Upvotes: 0