Untitled
unknown
plain_text
3 years ago
2.7 kB
4
Indexable
package mongodb;
import java.util.*;
import org.bson.*;
import com.mongodb.client.*;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
public class mongomau{
public static MongoClient mongo;
public static MongoCredential credential;
public static MongoDatabase db;
public static MongoCollection<Document> collection;
public static FindIterable<Document> ft;
public static Iterator<Document> it;
public static List<Document> list;
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
mongo = new MongoClient("localhost", 27017);
credential = MongoCredential.createCredential("root", "root", "password".toCharArray());
System.out.println("Connected to the database successfully");
db = mongo.getDatabase("myDb");
System.out.println("Connected to db successfully");
collection = db.getCollection("ipl");
while (true) {
System.out.println("1. View\n2.Insert\n3.Update\n4.Delete\n\nEnter your option: ");
int ch = Integer.parseInt(sc.nextLine());
switch(ch) {
case 1:
retrieve(collection);
break;
case 2:
insert(collection, sc);
retrieve(collection);
break;
case 3:
update(collection, sc);
retrieve(collection);
break;
case 4:
delete(collection, sc);
retrieve(collection);
break;
default:
System.out.println("Invalid choice:");
}
}
}
public static void retrieve(MongoCollection<Document> colleciton) {
ft = collection.find();
it = ft.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
}
public static void insert(MongoCollection<Document> collection, Scanner sc) {
System.out.println("Enter team name: ");
String tname = sc.nextLine();
System.out.println("Enter title won: ");
String twon = sc.nextLine();
System.out.println("Enter captain name: ");
String captain = sc.nextLine();
Document d = new Document("TeamName", tname).append("TitleWon", twon).append("Captain", captain);
collection.insertOne(d);
}
public static void update(MongoCollection<Document> collection, Scanner sc) {
System.out.println("Enter team name: ");
String tname = sc.nextLine();
System.out.println("Enter new number of : ");
String ntwon = sc.nextLine();
collection.updateOne(Filters.eq("TeamName", tname), Updates.set("TitlesWon", ntwon));
}
public static void delete(MongoCollection<Document> collection, Scanner sc) {
System.out.println("Enter team name: ");
String tname = sc.nextLine();
collection.deleteOne(Filters.eq("TeamName", tname));
}
}Editor is loading...