下面列出了怎么用com.mongodb.client.MongoCursor的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Provide existing Named Event Queries
*/
@RequestMapping(value = "/Admin/NamedEventQuery", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<?> getNamedEventQueries() {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.add("Content-Type", "application/json; charset=utf-8");
MongoCollection<BsonDocument> collection = Configuration.mongoDatabase.getCollection("NamedEventQuery",
BsonDocument.class);
MongoCursor<BsonDocument> cursor = collection.find().iterator();
JSONArray jarray = new JSONArray();
while (cursor.hasNext()) {
BsonDocument doc = cursor.next();
JSONObject json = new JSONObject(doc.toJson());
jarray.put(json);
}
return new ResponseEntity<>(jarray.toString(1), responseHeaders, HttpStatus.OK);
}
private List<String> getDistinctIdsForField(final MatchCollectionId collectionId,
final String fieldName) {
MongoUtil.validateRequiredParameter("collectionId", collectionId);
final List<String> distinctIds = new ArrayList<>(8096);
final MongoCollection<Document> collection = getExistingCollection(collectionId);
try (final MongoCursor<String> cursor = collection.distinct(fieldName, String.class).iterator()) {
while (cursor.hasNext()) {
distinctIds.add(cursor.next());
}
}
return distinctIds;
}
@Override
public AclEntity getAcl(String topic, String username, String clientId) {
FindIterable<Document> findIterable = aclCollection.find(eq("username", username));
MongoCursor<Document> cursor = findIterable.iterator();
AclEntity acl = null;
if(cursor.hasNext()) {
Document document = cursor.next();
acl = new AclEntity();
acl.username = username;
acl.clientId = clientId;
acl.topic = topic;
acl.canPublish = (document.getInteger("write") == 1);
acl.canSubscribe = (document.getInteger("read") == 1);
}
cursor.close();
return acl;
}
/**
* 查询所有记录 代码控制返回结果数
*
* @param table 表连接
* @param filter 条件 com.mongodb.client.model.Filter
* @param sort 排序 com.mongodb.client.model.Sorts 可空
* @return
*/
public List<JSONObject> getAll(MongoCollection table, Bson filter, Bson sort) {
List<JSONObject> list = new ArrayList<JSONObject>();
FindIterable<Document> result = null;
if (filter == null) {
result = table.find().sort(sort);
} else {
result = table.find(filter).sort(sort);
}
MongoCursor<Document> iterator = result.iterator();
while (iterator.hasNext()) {
Object ddd = iterator.next();
list.add(JSON.parseObject(diyObjectIdToJson(ddd)));
}
return list;
}
/**
* @decription 查询数据库表名
* @author yi.zhang
* @time 2017年6月30日 下午2:16:02
* @param table 表名
* @return
*/
public List<String> queryTables(){
try {
if(session==null){
init(servers, database, schema, username, password);
}
MongoIterable<String> collection = session.listCollectionNames();
if (collection == null) {
return null;
}
List<String> tables = new ArrayList<String>();
MongoCursor<String> cursor = collection.iterator();
while(cursor.hasNext()){
String table = cursor.next();
tables.add(table);
}
return tables;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* Geospatial query
*
* @param key should be indexed by 2dsphere
* db.vertices.createIndex({"urn:oliot:ubv:mda:gps" : "2dsphere"})
* @param lon
* @param lat
* @param radius in metres db.vertices.find({ "urn:oliot:ubv:mda:gps" : { $near
* : { $geometry: { type: "Point", coordinates: [ -1.1673,52.93]},
* $maxDistance: 50000}}})
*
* @return
*/
public HashSet<ChronoVertex> getChronoVertexSet(String key, double lon, double lat, double radius) {
HashSet<ChronoVertex> ret = new HashSet<ChronoVertex>();
BsonArray coordinates = new BsonArray();
coordinates.add(new BsonDouble(lon));
coordinates.add(new BsonDouble(lat));
BsonDocument geometry = new BsonDocument();
geometry.put("type", new BsonString("Point"));
geometry.put("coordinates", coordinates);
BsonDocument near = new BsonDocument();
near.put("$geometry", geometry);
near.put("$maxDistance", new BsonDouble(radius));
BsonDocument geoquery = new BsonDocument();
geoquery.put("$near", near);
BsonDocument queryDoc = new BsonDocument();
queryDoc.put(key, geoquery);
MongoCursor<BsonDocument> cursor = vertices.find(queryDoc).projection(Tokens.PRJ_ONLY_ID).iterator();
while (cursor.hasNext()) {
BsonDocument v = cursor.next();
ret.add(new ChronoVertex(v.getString(Tokens.ID).getValue(), this));
}
return ret;
}
/**
* 根据oid去数据库回查数据
*
* @param oid
* @return
*/
private Document fetchData(String schemaName, String tableName, String oid) {
Document result = null;
DbusDatasource datasource = GlobalCache.getDatasource();
MongoClientURI uri = new MongoClientURI(datasource.getMasterUrl());
MongoClient client = new MongoClient(uri);
MongoDatabase database = client.getDatabase(schemaName);
MongoCollection<Document> collection = database.getCollection(tableName);
MongoCursor<Document> cursor = collection.find(new BasicDBObject().append("_id", new ObjectId(oid))).iterator();
if (cursor.hasNext()) {
result = cursor.next();
} else {
logger.error("get source data error. schemaName:{}, tableName:{}, oid:{}", schemaName, tableName, oid);
}
client.close();
return result;
}
/**
* Attempts loading a world from mongoDB by coordinates
*
* @param x the x coordinate of the world
* @param y the y coordinate of the world
*
* @return World, null if not found
*/
private World loadWorld(int x, int y, String dimension) {
MongoDatabase db = mongo.getDatabase(GameServer.INSTANCE.getConfig().getString("mongo_dbname"));
MongoCollection<Document> worlds = db.getCollection("world");
Document whereQuery = new Document();
whereQuery.put("_id", World.idFromCoordinates(x, y, dimension));
MongoCursor<Document> cursor = worlds.find(whereQuery).iterator();
if (cursor.hasNext()) {
return World.deserialize(cursor.next());
}
else{
return null;
}
}
/**
* 根据统计字段计算统计结果(gte最小值)并排序
*
* @param collectionName 集合名
* @param match match条件
* @param field 统计字段
* @param minCount 最小值
* @return
*/
public LinkedHashMap<String, Integer> sortMap(String collectionName, Document match, String field, int minCount) {
AggregateIterable<Document> aggregate = getDB().getCollection(collectionName).aggregate(
Arrays.asList(
match(match)
, group("$" + field, Accumulators.sum("_count", 1))
, match(new Document("_count", new Document("$gte", minCount)))
, sort(new Document("_count", -1))
)
);
LinkedHashMap<String, Integer> map = new LinkedHashMap<String, Integer>();
MongoCursor<Document> iterator = aggregate.iterator();
while (iterator.hasNext()) {
Document next = iterator.next();
map.put(next.getString("_id"), next.getInteger("_count"));
}
return map;
}
@Override
long executeQuery(int threadId, long threadRunCount, long globalRunCount, long selectorId, long randomId){
final MongoCursor<Document> cursor = mongoCollection.find(eq(queriedField, selectorId)).iterator();
//final MongoCursor<Document> cursor = mongoCollection.find(in(queriedField, selectorId, selectorId+1, selectorId+2, selectorId+3, selectorId+4)).iterator();
long result = 0;
try {
while (cursor.hasNext()) {
final Document doc = cursor.next();
LOG.debug("Document {}", doc.toJson());
result++;
}
} finally {
cursor.close();
}
return result;
}
@Override
public <N extends Node> List<NodeEntry<UUID, N>> searchUserNodes(ConstraintNodeMatcher<N> constraint) throws Exception {
List<NodeEntry<UUID, N>> held = new ArrayList<>();
MongoCollection<Document> c = this.database.getCollection(this.prefix + "users");
try (MongoCursor<Document> cursor = c.find().iterator()) {
while (cursor.hasNext()) {
Document d = cursor.next();
UUID holder = getDocumentId(d);
Set<Node> nodes = new HashSet<>(nodesFromDoc(d));
for (Node e : nodes) {
N match = constraint.match(e);
if (match != null) {
held.add(NodeEntry.of(holder, match));
}
}
}
}
return held;
}
public void testDatabase() {
ListDatabasesIterable<Document> list = mongoClient.listDatabases();
MongoCursor<Document> iterD = list.iterator();
while (iterD.hasNext()) {
Document doc = iterD.next();
System.out.println(doc);
if (!doc.getBoolean("empty", true)) {
System.out.println(mongoClient.getDatabase(doc
.getString("name")));
}
}
// MongoIterable<String> mongo = mongoClient.listDatabaseNames();
// MongoCursor<String> iter = mongo.iterator();
// while (iter.hasNext()) {
// System.out.println(iter.next());
// }
}
@Override
public <N extends Node> List<NodeEntry<String, N>> searchGroupNodes(ConstraintNodeMatcher<N> constraint) throws Exception {
List<NodeEntry<String, N>> held = new ArrayList<>();
MongoCollection<Document> c = this.database.getCollection(this.prefix + "groups");
try (MongoCursor<Document> cursor = c.find().iterator()) {
while (cursor.hasNext()) {
Document d = cursor.next();
String holder = d.getString("_id");
Set<Node> nodes = new HashSet<>(nodesFromDoc(d));
for (Node e : nodes) {
N match = constraint.match(e);
if (match != null) {
held.add(NodeEntry.of(holder, match));
}
}
}
}
return held;
}
@Override
public void loadAllTracks() {
List<String> tracks = new ArrayList<>();
MongoCollection<Document> c = this.database.getCollection(this.prefix + "tracks");
try (MongoCursor<Document> cursor = c.find().iterator()) {
while (cursor.hasNext()) {
String name = cursor.next().getString("_id");
tracks.add(name);
}
}
if (!Iterators.tryIterate(tracks, this::loadTrack)) {
throw new RuntimeException("Exception occurred whilst loading a track");
}
this.plugin.getTrackManager().retainAll(tracks);
}
/**
* @return
*/
public List<Park> getAll() {
System.out.println("[DEBUG] MongoDBConnection.getAll()");
ArrayList<Park> allParksList = new ArrayList<Park>();
if (mongoDB != null) {
try {
MongoCollection parks = mongoDB.getCollection(COLLECTION);
MongoCursor<Document> cursor = parks.find().iterator();
try {
while (cursor.hasNext()) {
allParksList.add(ParkReadConverter.convert(cursor.next()));
}
} finally {
cursor.close();
}
} catch (Exception e) {
System.out.println("[ERROR] Error connecting to MongoDB. " + e.getMessage());
}
} else {
System.out.println("[ERROR] mongoDB could not be initiallized. No operation with DB will be performed");
}
return allParksList;
}
/**
* @param query
* @return
*/
public List<Park> getByQuery(BasicDBObject query) {
System.out.println("[DEBUG] MongoDBConnection.getByQuery()");
List<Park> parks = new ArrayList<Park>();
if (mongoDB != null) {
try {
MongoCursor<Document> cursor = mongoDB.getCollection(COLLECTION).find(query).iterator();
int i = 0;
try {
while (cursor.hasNext()) {
parks.add(ParkReadConverter.convert(cursor.next()));
}
} finally {
cursor.close();
}
} catch (Exception e) {
System.out.println("[ERROR] Error connecting to MongoDB. " + e.getMessage());
}
} else {
System.out.println("[ERROR] mongoDB could not be initiallized. No operation with DB will be performed");
}
return parks;
}
private List<TransformSpec> getTransformSpecs(final MongoCollection<Document> transformCollection,
final Set<String> specIds) {
final int specCount = specIds.size();
final List<TransformSpec> transformSpecList = new ArrayList<>(specCount);
if (specCount > 0) {
final Document transformQuery = new Document();
transformQuery.put("id", new Document(QueryOperators.IN, specIds));
LOG.debug("getTransformSpecs: {}.find({})",
MongoUtil.fullName(transformCollection), transformQuery.toJson());
try (final MongoCursor<Document> cursor = transformCollection.find(transformQuery).iterator()) {
Document document;
TransformSpec transformSpec;
while (cursor.hasNext()) {
document = cursor.next();
transformSpec = TransformSpec.fromJson(document.toJson());
transformSpecList.add(transformSpec);
}
}
}
return transformSpecList;
}
public boolean collectionExists(String collectionName) {
if (this.database == null) {
return false;
}
final MongoIterable<String> iterable = database.listCollectionNames();
try (final MongoCursor<String> it = iterable.iterator()) {
while (it.hasNext()) {
if (it.next().equalsIgnoreCase(collectionName)) {
return true;
}
}
}
return false;
}
/**
* Return an iterable to all the edges in the graph. If this is not possible for
* the implementation, then an UnsupportedOperationException can be thrown.
*
* @return
*
* @return an iterable reference to all edges in the graph
*/
public Stream<ChronoEdge> getChronoEdgeStream(boolean isParallel) {
HashSet<ChronoEdge> ret = new HashSet<ChronoEdge>();
MongoCursor<BsonDocument> cursor = edges.find().projection(Tokens.PRJ_ONLY_OUTV_LABEL_INV).iterator();
while (cursor.hasNext()) {
BsonDocument v = cursor.next();
String outV = v.getString(Tokens.OUT_VERTEX).getValue();
String label = v.getString(Tokens.LABEL).getValue();
String inV = v.getString(Tokens.IN_VERTEX).getValue();
String id = outV + "|" + label + "|" + inV;
ret.add(new ChronoEdge(id, outV, inV, label, this));
}
if (isParallel)
return ret.parallelStream();
else
return ret.stream();
}
private SetMultimap<ReNounFact, ScoredPattern> getFactToScoredPatternMultimap(
MongoCollection<Document> factsCollection,
MongoCollection<Document> scoredPatternsCollection) {
SetMultimap<ReNounFact, ScoredPattern> factToPatternMap = HashMultimap.create();
MongoCursor<Document> scoredPatternsCursor = scoredPatternsCollection.find().iterator();
while (scoredPatternsCursor.hasNext()) {
Document scoredPatternDocument = scoredPatternsCursor.next();
Iterator<Document> factsMatchingScoredPatternIterator =
factsCollection
.find(eq(PATTERN_FACT_FIELD, scoredPatternDocument.get(PATTERN_FACT_FIELD)))
.iterator();
while (factsMatchingScoredPatternIterator.hasNext()) {
Document factMatchingScoredPattern = factsMatchingScoredPatternIterator.next();
ReNounFact fact = new ReNounFact(factMatchingScoredPattern);
ScoredPattern scoredPattern = new ScoredPattern(scoredPatternDocument);
factToPatternMap.put(fact, scoredPattern);
}
}
return factToPatternMap;
}
public List<Document> getDocuments(BasicDBObject query, RESOURCE_TYPE resType, String sortKey, boolean asc, int limit) {
ArrayList<Document> docList = new ArrayList<Document>();
BasicDBObject sort = new BasicDBObject(sortKey, asc ? 1 : -1);
MongoCollection<Document> collection = context.getDatabaseManager()
.getCollection(collectionName);
MongoCursor<Document> cursor = collection.find(query).sort(sort)
.limit(limit).iterator();
while (cursor.hasNext()) {
docList.add(cursor.next());
}
return docList;
}
@Test
public void testSeedPatterns()
throws AnalysisEngineProcessException, ResourceInitializationException {
jCas.setDocumentText(
SENTENCE_1
+ SENTENCE_2
+ SENTENCE_3
+ SENTENCE_4
+ SENTENCE_5
+ SENTENCE_6
+ SENTENCE_7
+ SENTENCE_8);
processJCas();
MongoCursor<Document> found = output.find().iterator();
assertTrue(found.hasNext());
int count = 0;
while (found.hasNext()) {
count++;
Document next = found.next();
assertEquals("Google", next.get(SUBJECT_FIELD));
assertEquals("CEO", next.get(ATTRIBUTE_FIELD));
assertEquals("Larry Page", next.get(OBJECT_FIELD));
assertNotNull(next.get(SENTENCE_FIELD));
assertNotNull(next.get(PATTERN_FIELD));
}
assertEquals(8, count);
}
/**
* List databases in your DocumentDB instance treating each as a 'schema' (aka database)
*
* @see GlueMetadataHandler
*/
@Override
public ListSchemasResponse doListSchemaNames(BlockAllocator blockAllocator, ListSchemasRequest request)
{
List<String> schemas = new ArrayList<>();
MongoClient client = getOrCreateConn(request);
try (MongoCursor<String> itr = client.listDatabaseNames().iterator()) {
while (itr.hasNext()) {
schemas.add(itr.next());
}
return new ListSchemasResponse(request.getCatalogName(), schemas);
}
}
/**
* List collections in the requested schema in your DocumentDB instance treating the requested schema as an DocumentDB
* database.
*
* @see GlueMetadataHandler
*/
@Override
public ListTablesResponse doListTables(BlockAllocator blockAllocator, ListTablesRequest request)
{
MongoClient client = getOrCreateConn(request);
List<TableName> tables = new ArrayList<>();
try (MongoCursor<String> itr = client.getDatabase(request.getSchemaName()).listCollectionNames().iterator()) {
while (itr.hasNext()) {
tables.add(new TableName(request.getSchemaName(), itr.next()));
}
return new ListTablesResponse(request.getCatalogName(), tables);
}
}
public MongoCursor<Document> execute(MongoTableHandle tableHandle, List<MongoColumnHandle> columns)
{
Document output = new Document();
for (MongoColumnHandle column : columns) {
output.append(column.getName(), 1);
}
MongoCollection<Document> collection = getCollection(tableHandle.getSchemaTableName());
FindIterable<Document> iterable = collection.find(buildQuery(tableHandle.getConstraint())).projection(output);
if (cursorBatchSize != 0) {
iterable.batchSize(cursorBatchSize);
}
return iterable.iterator();
}
private Set<String> getTableMetadataNames(String schemaName)
throws TableNotFoundException
{
MongoDatabase db = client.getDatabase(schemaName);
MongoCursor<Document> cursor = db.getCollection(schemaCollection)
.find().projection(new Document(TABLE_NAME_KEY, true)).iterator();
HashSet<String> names = new HashSet<>();
while (cursor.hasNext()) {
names.add((cursor.next()).getString(TABLE_NAME_KEY));
}
return names;
}
public void close() {
if (cursor instanceof MongoCursor) {
((MongoCursor) cursor).close();
}
// AggregationOutput implements Iterator but not DBCursor. There is no
// available close() method -- apparently there is no open resource.
}
private int updateMatches(final List<MongoCursor<Document>> cursorList,
final List<CanvasMatches> matchesList,
final int index) {
CanvasMatches canvasMatches = null;
final MongoCursor<Document> cursor = cursorList.get(index);
if (cursor.hasNext()) {
canvasMatches = CanvasMatches.fromJson(cursor.next().toJson());
}
matchesList.set(index, canvasMatches);
return (canvasMatches == null ? 1 : 0);
}
private MongoCursor<BsonDocument> tryCreateCursor(
final MongoSourceConfig sourceConfig,
final MongoClient mongoClient,
final BsonDocument resumeToken) {
try {
ChangeStreamIterable<Document> changeStreamIterable =
getChangeStreamIterable(sourceConfig, mongoClient);
if (resumeToken != null && supportsStartAfter) {
LOGGER.info("Resuming the change stream after the previous offset: {}", resumeToken);
changeStreamIterable.startAfter(resumeToken);
} else if (resumeToken != null && !invalidatedCursor) {
LOGGER.info("Resuming the change stream after the previous offset using resumeAfter.");
changeStreamIterable.resumeAfter(resumeToken);
} else {
LOGGER.info("New change stream cursor created without offset.");
}
return changeStreamIterable.withDocumentClass(BsonDocument.class).iterator();
} catch (MongoCommandException e) {
if (resumeToken != null) {
if (e.getErrorCode() == 260) {
invalidatedCursor = true;
return tryCreateCursor(sourceConfig, mongoClient, null);
} else if ((e.getErrorCode() == 9 || e.getErrorCode() == 40415)
&& e.getErrorMessage().contains("startAfter")) {
supportsStartAfter = false;
return tryCreateCursor(sourceConfig, mongoClient, resumeToken);
}
}
LOGGER.info("Failed to resume change stream: {} {}", e.getErrorMessage(), e.getErrorCode());
return null;
}
}
/**
* 数据库对应的数据集合列表
* @param dbName
* @return
*/
@ResponseBody
@RequestMapping("/db")
public Res db(String dbName) {
if(StringUtils.isEmpty(dbName)){
return Res.error("dbName参数不能为空");
}
if("undefined".equals(dbName)){
return Res.error("请关闭所有的iframe后在执行F5");
}
MongoDatabase mogo = mongoSdkBase.getMongoDb(dbName);
//获取所有集合的名称
MongoIterable<String> collectionNames = mogo.listCollectionNames();
MongoCursor<String> i = collectionNames.iterator();
List<JSONObject> listNames = new ArrayList<JSONObject>();
while (i.hasNext()) {
String tableName = i.next();
if(!Arrays.asList(TAVLEARR).contains(tableName)) {
JSONObject t = new JSONObject();
t.put("tableName", tableName);
BasicDBObject obj = mongoSdkBase.getStats(dbName, tableName);
t.put("size", ByteConvKbUtils.getPrintSize(obj.getInt("size")));
listNames.add(t);
}
}
return Res.ok().put("listNames", listNames);
}