下面列出了怎么用com.mongodb.client.FindIterable的API类实例代码及写法,或者点击链接到github查看源代码。
protected MDbResultSet execute() throws OdaException
{
if( m_queryObj == null || m_queryCollection == null )
throw new OdaException( Messages.mDbOp_invalidQueryExpr );
try
{
FindIterable<Document> findIterable = m_queryCollection.find( m_queryObj);
findIterable = findIterable.projection( m_fieldsObj );
// no search limit applies here;
// defer to MDbResultSet to set DBCursor#limit based on its maxRows
applyPropertiesToCursor( findIterable, getModel().getQueryProperties(), false, true );
return new MDbResultSet( findIterable.iterator(), getResultSetMetaData(), getModel().getQueryProperties() );
}
catch( RuntimeException ex )
{
DriverUtil.getLogger().log( Level.SEVERE, "Encountered RuntimeException: ", ex ); //$NON-NLS-1$
throw new OdaException( ex );
}
}
private void applyPropertiesToCursor( MongoIterable<Document> mongoIterable, QueryProperties queryProps,
boolean includeMetaDataSearchLimit, boolean includeSortExpr )
{
if( includeMetaDataSearchLimit )
{
Integer searchLimit = getModel().getEffectiveMDSearchLimit( queryProps );
if( searchLimit > 0 )
{
// Apply to FindIterable or MapReduceIterable
if ( mongoIterable instanceof FindIterable )
{
FindIterable<Document> findIterable = (FindIterable<Document>) mongoIterable;
findIterable.limit( searchLimit.intValue( ) );
}
else if ( mongoIterable instanceof MapReduceIterable )
{
MapReduceIterable<Document> mapReduceIterable = (MapReduceIterable<Document>) mongoIterable;
mapReduceIterable.limit( searchLimit.intValue( ) );
}
}
}
applyPropertiesToCursor( mongoIterable, queryProps, includeSortExpr );
}
/**
* Executes a "find" operation on the underlying collection.
*
* <p>For example,
* <code>zipsTable.find("{state: 'OR'}", "{city: 1, zipcode: 1}")</code></p>
*
* @param mongoDb MongoDB connection
* @param filterJson Filter JSON string, or null
* @param projectJson Project JSON string, or null
* @param fields List of fields to project; or null to return map
* @return Enumerator of results
*/
private Enumerable<Object> find(MongoDatabase mongoDb, String filterJson,
String projectJson, List<Map.Entry<String, Class>> fields) {
final MongoCollection collection =
mongoDb.getCollection(collectionName);
final Bson filter =
filterJson == null ? null : BsonDocument.parse(filterJson);
final Bson project =
projectJson == null ? null : BsonDocument.parse(projectJson);
final Function1<Document, Object> getter = MongoEnumerator.getter(fields);
return new AbstractEnumerable<Object>() {
public Enumerator<Object> enumerator() {
@SuppressWarnings("unchecked") final FindIterable<Document> cursor =
collection.find(filter).projection(project);
return new MongoEnumerator(cursor.iterator(), getter);
}
};
}
/**
* 查询所有记录 代码控制返回结果数
*
* @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;
}
private void manageOffsets(FindIterable find, Integer limit) {
if (range != null) {
find.skip(range.getStartIndex());
if (limit == null) {
// range is 0 based, so we add 1 to the limit
find.limit(range.getLastIndex() - range.getStartIndex() + 1);
}
} else if (page != null) {
find.skip(page.index * page.size);
if (limit == null) {
find.limit(page.size);
}
}
if (limit != null) {
find.limit(limit);
}
}
@Override
public JSONArray find(String key, String collection, JSONObject where, int limit, int skip) {
MongoCollection<Document> mc = getCollection(key, collection);
if (mc == null)
return new JSONArray();
FindIterable<Document> fi = mc.find(toDocument(where));
if (limit > 0)
fi.limit(limit);
if (skip > 0)
fi.skip(skip);
JSONArray array = new JSONArray();
for (Document document : fi)
array.add(JSON.parseObject(document.toJson()));
return array;
}
@Test
public void queryAll() {
// @begin: query-all
// @code: start
FindIterable<Document> iterable = db.getCollection("restaurants").find();
// @code: end
// @pre: Iterate the results and apply a block to each resulting document.
// @code: start
iterable.forEach(new Block<Document>() {
@Override
public void apply(final Document document) {
System.out.println(document.toJson());
}
});
// @code: end
// @end: query-all
}
@Test
public void logicalAnd() {
// @begin: logical-and
// @code: start
FindIterable<Document> iterable = db.getCollection("restaurants")
.find(new Document("cuisine", "Italian").append("address.zipcode", "10075"));
// @code: end
// @pre: Iterate the results and apply a block to each resulting document.
// @code: start
iterable.forEach(new Block<Document>() {
@Override
public void apply(final Document document) {
System.out.println(document);
}
});
// @code: end
// @pre: To simplify building queries the Java driver provides static helpers
// @code: start
db.getCollection("restaurants").find(and(eq("cuisine", "Italian"), eq("address.zipcode", "10075")));
// @code: end
// @end: logical-and
}
@Test
public void queryTopLevelField() {
// @begin: query-top-level-field
// @code: start
FindIterable<Document> iterable = db.getCollection("restaurants").find(new Document("borough", "Manhattan"));
// @code: end
// @pre: Iterate the results and apply a block to each resulting document.
// @code: start
iterable.forEach(new Block<Document>() {
@Override
public void apply(final Document document) {
System.out.println(document);
}
});
// @code: end
// @pre: To simplify building queries the Java driver provides static helpers
// @code: start
db.getCollection("restaurants").find(eq("borough", "Manhattan"));
// @code: end
// @end: query-top-level-field
}
@Test
public void queryEmbeddedDocument() {
// @begin: query-embedded-document
// @code: start
FindIterable<Document> iterable = db.getCollection("restaurants")
.find(new Document("address.zipcode", "10075"));
// @code: end
// @pre: Iterate the results and apply a block to each resulting document.
// @code: start
iterable.forEach(new Block<Document>() {
@Override
public void apply(final Document document) {
System.out.println(document);
}
});
// @code: end
// @pre: To simplify building queries the Java driver provides static helpers
// @code: start
db.getCollection("restaurants").find(eq("address.zipcode", "10075"));
// @code: end
// @end: query-embedded-document
}
@Test
public void greaterThan() {
// @begin: greater-than
// @code: start
FindIterable<Document> iterable = db.getCollection("restaurants")
.find(new Document("grades.score", new Document("$gt", 30)));
// @code: end
// @pre: Iterate the results and apply a block to each resulting document.
// @code: start
iterable.forEach(new Block<Document>() {
@Override
public void apply(final Document document) {
System.out.println(document);
}
});
// @code: end
// @pre: To simplify building queries the Java driver provides static helpers
// @code: start
db.getCollection("restaurants").find(gt("grades.score", 30));
// @code: end
// @end: greater-than
}
private static void extractVersionedIds(List<IResourceId> versionedIds,
FindIterable<Document> documentIterable) {
for (Document document : documentIterable) {
Object idObject = document.get(MONGO_OBJECT_ID);
String objectId = ((Document) idObject).getObjectId(MONGO_OBJECT_ID).toString();
Integer objectVersion = ((Document) idObject).getInteger(MONGO_OBJECT_VERSION);
versionedIds.add(new IResourceId() {
@Override
public String getId() {
return objectId;
}
@Override
public Integer getVersion() {
return objectVersion;
}
});
}
}
@Override
public IHistoryResource<T> readHistoryLatest(String id) {
Document beginId = new Document();
beginId.put(ID_FIELD, new ObjectId(id));
beginId.put(VERSION_FIELD, 0);
Document endId = new Document();
endId.put(ID_FIELD, new ObjectId(id));
endId.put(VERSION_FIELD, Integer.MAX_VALUE);
Document query = new Document();
query.put("$gt", beginId);
query.put("$lt", endId);
Document object = new Document();
object.put(ID_FIELD, query);
if (historyCollection.countDocuments(object) == 0) {
return null;
}
FindIterable<Document> documents = historyCollection.find(object).sort(new Document(ID_FIELD, -1)).limit(1);
return new HistoryResource(documents.iterator().next());
}
private String getTransactionOwnerInMongoDB(TransactionXid transactionXid) {
byte[] global = transactionXid.getGlobalTransactionId();
String instanceId = ByteUtils.byteArrayToString(global);
try {
String application = CommonUtils.getApplication(this.endpoint);
String databaseName = application.replaceAll("\\W", "_");
MongoDatabase mdb = this.mongoClient.getDatabase(databaseName);
MongoCollection<Document> collection = mdb.getCollection(CONSTANTS_TB_LOCKS);
FindIterable<Document> findIterable = collection.find(Filters.eq(CONSTANTS_FD_GLOBAL, instanceId));
MongoCursor<Document> cursor = findIterable.iterator();
if (cursor.hasNext()) {
Document document = cursor.next();
return document.getString("identifier");
} else {
return null;
}
} catch (RuntimeException rex) {
logger.error("Error occurred while querying the lock-owner of transaction(gxid= {}).", instanceId, rex);
return null;
}
}
private Iterator<Instance> getDocumentsFromMongo() {
FindIterable<Document> find = documentsCollection.find();
return FluentIterable.from(new MongoIterable(find))
.transform(
d -> {
String name = d.getObjectId("_id").toHexString();
String data = d.getString(contentField);
Optional<String> label = getLabel(d);
if (!label.isPresent()) {
Document metadata = (Document) d.get(Mongo.FIELD_METADATA);
label = getLabel(metadata);
}
return new Instance(data, label.orElse("UNKNOWN"), name, null);
})
.iterator();
}
@Test
public void testRecords()
throws JsonParseException, JsonMappingException, IOException, AnalysisEngineProcessException {
process();
FindIterable<Document> find = recordsCollection.find();
Document document = find.first();
String json = document.toJson();
ObjectMapper mapper = new ObjectMapper();
MongoExtractedRecords mongoRecords = mapper.readValue(json, MongoExtractedRecords.class);
assertEquals(
"17e5e009b415a7c97e35f700fe9c36cc67c1b8a8457a1136e6b9eca001cd361a",
mongoRecords.getExternalId());
assertEquals("MongoTemplateRecordConsumer.txt", mongoRecords.getSourceUri());
Map<String, Collection<ExtractedRecord>> records = mongoRecords.getRecords();
checkRecords(records);
}
/**
* List the document Ids of the PCJs that are stored in MongoDB
* for this instance of Rya.
*
* @return A list of pcj document Ids that hold PCJ index data for the current
* instance of Rya.
*/
public List<String> listPcjDocuments() {
final List<String> pcjIds = new ArrayList<>();
//This Bson string reads as:
//{} - no search criteria: find all
//{ _id: 1 } - only return the _id, which is the PCJ Id.
final FindIterable<Document> rez = pcjCollection.find(Document.parse("{ }, { " + PCJ_METADATA_ID + ": 1 , _id: 0}"));
try (final MongoCursor<Document> cursor = rez.iterator()) {
while(cursor.hasNext()) {
final Document doc = cursor.next();
final String pcjMetadataId = doc.get(PCJ_METADATA_ID).toString();
pcjIds.add(pcjMetadataId.replace(METADATA_ID_SUFFIX, ""));
}
}
return pcjIds;
}
public List<XbddFeatureSummary> getFeatureSummaries(final Coordinates coordinates) {
final MongoCollection<XbddFeature> features = getFeatureCollection();
final List<XbddFeatureSummary> summaries = new ArrayList<>();
final Bson query = Filters.eq("coordinates", CoordinatesMapper.mapCoordinates(coordinates));
final FindIterable<XbddFeatureSummary> savedFeatures = features.find(query, XbddFeatureSummary.class);
final Consumer<XbddFeatureSummary> addToSummaries = feature -> {
if (featureIsValid(feature)) {
summaries.add(feature);
}
};
savedFeatures.forEach(addToSummaries);
return summaries;
}
public List<XbddFeature> getFeatures(final Coordinates coordinates) {
final MongoCollection<XbddFeature> features = getFeatureCollection();
final List<XbddFeature> extractedFeatures = new ArrayList<>();
final Bson query = Filters.eq("coordinates", CoordinatesMapper.mapCoordinates(coordinates));
final FindIterable<XbddFeature> savedFeatures = features.find(query, XbddFeature.class);
final Consumer<XbddFeature> addToExtractedFeatures = feature -> {
if (featureIsValid(feature)) {
extractedFeatures.add(feature);
}
};
savedFeatures.forEach(addToExtractedFeatures);
return extractedFeatures;
}
@Signature
public WrapMongoIterable maxAwaitTime(long millis) {
if (getWrappedObject() instanceof FindIterable) {
return new WrapMongoIterable(this.__env__, ((FindIterable) getWrappedObject()).maxAwaitTime(millis, TimeUnit.MILLISECONDS));
} else {
return this;
}
}
private <E> MongoCursor<E> prepareCursor(final FindOptions options, final MongoCollection<E> collection) {
final Document query = this.toDocument();
FindOptions findOptions = getOptions().copy().copy(options);
if (LOG.isTraceEnabled()) {
LOG.trace(format("Running query(%s) : %s, options: %s,", getCollectionName(), query, findOptions));
}
if ((findOptions.getCursorType() != null && findOptions.getCursorType() != NonTailable)
&& (findOptions.getSort() != null)) {
LOG.warn("Sorting on tail is not allowed.");
}
ClientSession clientSession = datastore.findSession(findOptions);
FindIterable<E> iterable = clientSession != null
? collection.find(clientSession, query)
: collection.find(query);
Document oldProfile = null;
if (findOptions.isLogQuery()) {
oldProfile = datastore.getDatabase().runCommand(new Document("profile", 2).append("slowms", 0));
}
try {
return findOptions
.apply(iterable, mapper, clazz)
.iterator();
} finally {
if (findOptions.isLogQuery()) {
datastore.getDatabase().runCommand(new Document("profile", oldProfile.get("was"))
.append("slowms", oldProfile.get("slowms"))
.append("sampleRate", oldProfile.get("sampleRate")));
}
}
}
@SuppressWarnings("unchecked")
@Test
void testProjection()
{
FindIterable<Document> projectionIterable = mock(FindIterable.class);
when(findIterable.projection(bson)).thenReturn(projectionIterable);
Object output = MongoCommand.PROJECTION.apply(Function.identity(), bson).apply(findIterable);
assertEquals(projectionIterable, output);
}
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();
}
/**
* Creates and returns the MongoDB {@link BatchSource}.
*/
@Nonnull
public BatchSource<U> build() {
checkNotNull(connectionSupplier, "connectionSupplier must be set");
checkNotNull(databaseFn, "databaseFn must be set");
checkNotNull(collectionFn, "collectionFn must be set");
checkNotNull(searchFn, "searchFn must be set");
checkNotNull(mapFn, "mapFn must be set");
SupplierEx<? extends MongoClient> localConnectionSupplier = connectionSupplier;
FunctionEx<? super MongoClient, ? extends MongoDatabase> localDatabaseFn = databaseFn;
FunctionEx<? super MongoDatabase, ? extends MongoCollection<? extends T>> localCollectionFn
= (FunctionEx<? super MongoDatabase, ? extends MongoCollection<? extends T>>) collectionFn;
ConsumerEx<? super MongoClient> localDestroyFn = destroyFn;
FunctionEx<? super MongoCollection<? extends T>, ? extends FindIterable<? extends T>> localSearchFn = searchFn;
FunctionEx<? super T, U> localMapFn = mapFn;
return SourceBuilder
.batch(name, ctx -> {
MongoClient client = localConnectionSupplier.get();
MongoCollection<? extends T> collection = localCollectionFn.apply(localDatabaseFn.apply(client));
return new BatchContext<>(client, collection, localSearchFn, localMapFn, localDestroyFn);
})
.<U>fillBufferFn(BatchContext::fillBuffer)
.destroyFn(BatchContext::close)
.build();
}
BatchContext(
MongoClient client,
MongoCollection<? extends T> collection,
FunctionEx<? super MongoCollection<? extends T>, ? extends FindIterable<? extends T>> searchFn,
FunctionEx<? super T, U> mapFn,
ConsumerEx<? super MongoClient> destroyFn
) {
this.client = client;
this.mapFn = mapFn;
this.destroyFn = destroyFn;
cursor = searchFn.apply(collection).iterator();
}
@Override
public String getSecret(String username) {
FindIterable<Document> findIterable = userCollection.find(eq("username", username)).limit(1);
MongoCursor<Document> cursor = findIterable.iterator();
String secret = null;
if(cursor.hasNext())
secret = cursor.next().getString("password");
cursor.close();
return secret;
}
@SuppressWarnings( "rawtypes" )
public cfData execute(cfSession _session, cfArgStructData argStruct ) throws cfmRunTimeException {
MongoDatabase db = getMongoDatabase( _session, argStruct );
String collection = getNamedStringParam(argStruct, "collection", null);
if ( collection == null )
throwException(_session, "please specify a collection");
cfData query = getNamedParam(argStruct, "query", null );
if ( query == null )
throwException(_session, "please specify query to find");
cfData fields = getNamedParam(argStruct, "fields", null );
try{
MongoCollection<Document> col = db.getCollection(collection);
long start = System.currentTimeMillis();
Document qry = getDocument(query);
FindIterable<Document> cursor = col.find( qry ).limit( 1 );
if ( fields != null )
cursor = cursor.projection( getDocument(fields) );
_session.getDebugRecorder().execMongo(col, "findone", qry, System.currentTimeMillis()-start);
return tagUtils.convertToCfData( (Map)cursor.first() );
} catch (MongoException me){
throwException(_session, me.getMessage());
return null;
}
}
private CloseableIterator<BindingSet> queryForBindings(final Document query) {
final FindIterable<Document> rez = pcjCollection.find(query);
final Iterator<Document> resultsIter = rez.iterator();
return new CloseableIterator<BindingSet>() {
@Override
public boolean hasNext() {
return resultsIter.hasNext();
}
@Override
public BindingSet next() {
final Document bs = resultsIter.next();
final MapBindingSet binding = new MapBindingSet();
for (final String key : bs.keySet()) {
if (key.equals(VISIBILITIES_FIELD)) {
// has auths, is a visibility binding set.
} else if (!key.equals("_id") && !key.equals(PCJ_ID)) {
// is the binding value.
final Document typeDoc = (Document) bs.get(key);
final IRI dataType = VF.createIRI(typeDoc.getString(BINDING_TYPE));
final RyaType type = new RyaType(dataType, typeDoc.getString(BINDING_VALUE));
final Value value = RyaToRdfConversions.convertValue(type);
binding.addBinding(key, value);
}
}
return binding;
}
@Override
public void close() throws Exception {
}
};
}
@Signature
public WrapMongoIterable maxTime(long millis) {
if (getWrappedObject() instanceof FindIterable) {
return new WrapMongoIterable(this.__env__, ((FindIterable) getWrappedObject()).maxTime(millis, TimeUnit.MILLISECONDS));
} else {
return this;
}
}
@Override
public List<User> findAll() {
return mongoDBUtil.execute(userCollectionName, collection -> {
FindIterable<Document> result = collection.find();
List<User> users = new ArrayList<>();
for (Document document : result) {
users.add(formUser(document));
}
return users;
});
}