import java.util.Arrays;
import java.util.List;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.ServerAddress;
public class MongoDB {
private static MongoClient client;
private static DBCollection collection;
private static void createCollection() throws UnknownHostException {
MongoDB.client = new MongoClient(new ServerAddress("localhost", 27017));
DB database = client.getDB("databaseName");
MongoDB.collection = database.getCollection("collectionName");
collection.drop();
}
public static void main(String[] args) throws UnknownHostException {
createCollection();
List<String> names = Arrays.asList("alice", "bobby", "cathy", "david",
"ethan");
for (String name : names) {
collection.insert(new BasicDBObject("_id", name));
}
printCollection();
System.out.println("==========");
collection.update(new BasicDBObject("_id", "alice"), new BasicDBObject(
"age", 24));
printCollection();
System.out.println("==========");
collection.update(new BasicDBObject("_id", "alice"), new BasicDBObject(
"gender", "F"));
printCollection();
System.out.println("==========");
collection.update(new BasicDBObject("_id", "bobby"), new BasicDBObject(
"$set", new BasicDBObject("age", "26")));
printCollection();
System.out.println("==========");
collection.update(new BasicDBObject("_id", "bobby"), new BasicDBObject(
"$set", new BasicDBObject("gender", "F")));
printCollection();
System.out.println("==========");
collection.update(new BasicDBObject("_id", "frank"), new BasicDBObject(
"$set", new BasicDBObject("gender", "F")), true, false);
printCollection();
System.out.println("==========");
collection.update(new BasicDBObject("_id", "frank"), new BasicDBObject(
"$set", new BasicDBObject("gender", "M")), true, false);
printCollection();
System.out.println("==========");
collection.update(new BasicDBObject(), new BasicDBObject("$set",
new BasicDBObject("title", "Dr.")), false, true);
printCollection();
System.out.println("==========");
collection.remove(new BasicDBObject("_id", "alice"));
printCollection();
System.out.println("==========");
collection.remove(new BasicDBObject());
printCollection();
System.out.println("==========");
client.close();
}
private static void printCollection() {
DBCursor result = null;
try {
result = collection.find();
while (result.hasNext()) {
DBObject document = result.next();
System.out.println(document);
}
} finally {
result.close();
}
}
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.