package com.mongo;
import java.net.UnknownHostException;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class MongoDBExample {
public static void main(String[] args) throws UnknownHostException {
createCollection();
}
public static void createCollection(){
User user = createUser();
Document doc = createDBObject(user);
MongoClient mongo = new MongoClient("localhost", 27017);
MongoDatabase db = mongo.getDatabase("test");
MongoCollection<Document> col = db.getCollection("users");
//create user
col.insertOne(doc);
}
private static Document createDBObject(User user) {
Document docBuilder = new Document();
docBuilder.append("_id", user.getId());
docBuilder.append("name", user.getName());
docBuilder.append("role", user.getRole());
docBuilder.append("isEmployee", user.isEmployee());
return docBuilder;
}
private static User createUser() {
User u = new User();
u.setId(2);
u.setName("Raj");
u.setEmployee(true);
u.setRole("CEO");
return u;
}
}
import java.net.UnknownHostException;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class MongoDBExample {
public static void main(String[] args) throws UnknownHostException {
createCollection();
}
public static void createCollection(){
User user = createUser();
Document doc = createDBObject(user);
MongoClient mongo = new MongoClient("localhost", 27017);
MongoDatabase db = mongo.getDatabase("test");
MongoCollection<Document> col = db.getCollection("users");
//create user
col.insertOne(doc);
}
private static Document createDBObject(User user) {
Document docBuilder = new Document();
docBuilder.append("_id", user.getId());
docBuilder.append("name", user.getName());
docBuilder.append("role", user.getRole());
docBuilder.append("isEmployee", user.isEmployee());
return docBuilder;
}
private static User createUser() {
User u = new User();
u.setId(2);
u.setName("Raj");
u.setEmployee(true);
u.setRole("CEO");
return u;
}
}
package com.mongo;
public class User {
private int id;
private String name;
private String role;
private boolean isEmployee;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public boolean isEmployee() {
return isEmployee;
}
public void setEmployee(boolean isEmployee) {
this.isEmployee = isEmployee;
}
}
No comments:
Post a Comment