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();
Random random = new Random();
for (int i = 0; i < 10; i++) {
collection.insert(new BasicDBObject("_id", i).append(
"start",
new BasicDBObject("x", random.nextInt(90) + 10).append("y",
random.nextInt(90) + 10)).append(
"end",
new BasicDBObject("x", random.nextInt(90) + 10).append("y",
random.nextInt(90) + 10)));
}
DBObject query = QueryBuilder.start().get();
show(query);
query = QueryBuilder.start("start.x").greaterThan(50).get();
show(query);
client.close();
}
private static void show(DBObject query) {
DBCursor result = null;
try {
result = collection.find(query);
showResult(result);
result = collection.find(query, new BasicDBObject("start.y", true));
showResult(result);
result = collection.find(query,
new BasicDBObject("start.y", true).append("_id", false));
showResult(result);
} finally {
result.close();
}
}
private static void showResult(DBCursor result) {
while (result.hasNext()) {
DBObject document = result.next();
System.out.println(document);
}
}
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.