import java.util.Random;
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.QueryBuilder;
import com.mongodb.ServerAddress;
public class MongoDB {
private static DBCollection collection;
public static void main(String[] args) throws UnknownHostException {
MongoClient client = new MongoClient(new ServerAddress("localhost",
27017));
DB database = client.getDB("databaseName");
collection = database.getCollection("collectionName");
collection.drop();
for (int i = 0; i < 10; i++) {
collection.insert(new BasicDBObject("x", new Random().nextInt(2))
.append("y", new Random().nextInt(100)));
}
DBObject query = new BasicDBObject("x", 0);
show(query);
query = new BasicDBObject("x", 0).append("y", new BasicDBObject("$gt",
10).append("$lt", 90));
show(query);
QueryBuilder queryBuilder = QueryBuilder.start("x").is(0).and("y")
.greaterThan(10).lessThan(90);
show(queryBuilder.get());
client.close();
}
private static void show(DBObject query) {
showCount(query);
showFind(query);
}
private static void showCount(DBObject query) {
long count = collection.count(query);
System.out.println(count);
}
private static void showFind(DBObject query) {
DBCursor find = collection.find(query);
try {
while (find.hasNext()) {
DBObject document = find.next();
System.out.println(document);
}
} finally {
find.close();
}
}
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.