-
Notifications
You must be signed in to change notification settings - Fork 0
/
Asgn_12.java
81 lines (75 loc) · 3.46 KB
/
Asgn_12.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import com.mongodb.*;
import java.util.Scanner;
public class Asgn_12 {
private static void choice_input() {
System.out.println("\n1. Insert data into the database\n2. Update database documents\n3. Delete database documents\n4. Show database collections\n5. Exit");
}
public static void main(String[] args) {
String key, value;
Scanner scanner = new Scanner(System.in);
int choice;
try {
MongoClient mongoClient = new MongoClient("10.10.10.176", 27017);
DB db = mongoClient.getDB("31253_db");
DBCollection collection = db.getCollection("Students");
do {
choice_input();
System.out.println("Enter your choice: ");
choice = scanner.nextInt();
switch (choice) {
case 1:
BasicDBObject document = new BasicDBObject();
String ch;
do {
System.out.println("Enter key: ");
key = scanner.next();
System.out.println("Enter value: ");
value = scanner.next();
document.put(key, value);
System.out.println("Do you want to enter more (y/n)? ");
ch = scanner.next();
} while (!ch.equals("n"));
collection.insert(document);
break;
case 2:
BasicDBObject searchObj = new BasicDBObject();
System.out.println("Enter searched key: ");
key = scanner.next();
System.out.println("Enter searched value: ");
value = scanner.next();
searchObj.put(key, value);
BasicDBObject newObj = new BasicDBObject();
System.out.println("Enter new key: ");
key = scanner.next();
System.out.println("Enter new value: ");
value = scanner.next();
newObj.put(key, value);
BasicDBObject updateQuery = new BasicDBObject("$set", newObj);
collection.update(searchObj, updateQuery);
break;
case 3:
System.out.println("Enter removable key: ");
key = scanner.next();
System.out.println("Enter removable value: ");
value = scanner.next();
BasicDBObject removableObj = new BasicDBObject(key, value);
collection.remove(removableObj);
break;
case 4:
DBCursor cursorDoc = collection.find();
while (cursorDoc.hasNext()) {
System.out.println(cursorDoc.next());
}
break;
case 5:
mongoClient.close();
scanner.close();
System.exit(0);
break;
}
} while (choice != 5);
} catch (MongoException e) {
e.printStackTrace();
}
}
}