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("x", random.nextInt(2)).append(
"y", random.nextInt(100)).append("z",
random.nextInt(1000)));
}
DBObject query = QueryBuilder.start("x").is(0).and("y").greaterThan(10)
.lessThan(90).get();
show(query);
client.close();
}
private static void show(DBObject query) {
DBCursor result = null;
try {
result = collection.find(query, new BasicDBObject("x", false));
showResult(result);
result = collection.find(query, new BasicDBObject("y", true));
showResult(result);
result = collection.find(query,
new BasicDBObject("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.