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;
public static void main(String[] args) throws UnknownHostException {
createCollection();
int first;
int numNeeded;
numNeeded = 2;
first = getRange(numNeeded);
printCollection();
System.out.println("Range: " + first + "-" + (first + numNeeded - 1));
numNeeded = 3;
first = getRange(numNeeded);
printCollection();
System.out.println("Range: " + first + "-" + (first + numNeeded - 1));
numNeeded = 10;
first = getRange(numNeeded);
printCollection();
System.out.println("Range: " + first + "-" + (first + numNeeded - 1));
client.close();
}
private static int getRange(int range) {
DBObject document = collection.findAndModify(new BasicDBObject("_id",
"abc"), null, null, false, new BasicDBObject("$inc",
new BasicDBObject("counter", range)), true, true);
return (Integer) document.get("counter") - range + 1;
}
private static void createCollection() throws UnknownHostException {
client = new MongoClient(new ServerAddress("localhost", 27017));
DB database = client.getDB("databaseName");
collection = database.getCollection("collectionName");
collection.drop();
}
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.