Queries for an object in this collection.

@param query object for which to search
@return an iterator over the results
@throws MongoException If an error occurred
975589
public DBCursor<T> find(DBObject query) throws MongoException {
        return new DBCursor<T>(this, dbCollection.find(serializeFields(query)));
    }
1261944
static Iterator<Page> lazySearch(final Wikipedia wikipedia, final String query) {
    final Response<Page> first = wikipedia.search(query);
    if (first.nextOffset == null) {
      return first.iterator();
    }
    return new Iterator<Page>() {
      Iterator<Page> current = first.iterator();
      Long nextOffset = first.nextOffset;

      @Override
      public boolean hasNext() {
        while (!current.hasNext() && nextOffset != null) {
          System.out.println("Wow.. even more results than " + nextOffset);
          Response<Page> nextPage = wikipedia.resumeSearch(query, nextOffset);
          current = nextPage.iterator();
          nextOffset = nextPage.nextOffset;
        }
        return current.hasNext();
      }

      @Override
      public Page next() {
        return current.next();
      }

      @Override
      public void remove() {
        throw new UnsupportedOperationException();
      }
    };
  }
641282
public String query(String query) {
        try {
            Connection conn = this.tx().getConnection();
            ObjectNode result = this.mapper.createObjectNode();
            ArrayNode dataNode = this.mapper.createArrayNode();
            ArrayNode metaNode = this.mapper.createArrayNode();
            Statement statement = conn.createStatement();
            if (logger.isDebugEnabled()) {
                logger.debug(query);
            }
            ResultSet rs = statement.executeQuery(query);
            ResultSetMetaData rsmd = rs.getMetaData();
            boolean first = true;
            while (rs.next()) {
                int numColumns = rsmd.getColumnCount();
                ObjectNode obj = this.mapper.createObjectNode();
                for (int i = 1; i < numColumns + 1; i++) {
                    String columnName = rsmd.getColumnLabel(i);
                    int type = rsmd.getColumnType(i);
                    //make sure to obtain array using getArray()
                    //At least in H2, this makes a difference...
                    Object o = type == Types.ARRAY ? rs.getArray(i) : rs.getObject(i);
                    this.sqlDialect.putJsonObject(obj, columnName, type, o);
                    if (first) {
                        this.sqlDialect.putJsonMetaObject(this.mapper, metaNode, columnName, type, o);
                    }
                }
                first = false;
                dataNode.add(obj);
            }
            result.set("data", dataNode);
            result.set("meta", metaNode);
            return result.toString();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            this.tx().rollback();
        }
    }
1347314
function collectionLookup (collection, query) {
	const id = createID(query.pattern, query.language);
	log(`collectionLookup: querying for ${id}`);
	return collection.find({_id: id}, {result: 1}).toArray()
		.then(
			(docs) => {
				log(`collectionLookup: Got ${docs.length} docs`);
				if (docs.length === 0) {
					log(`collectionLookup ${createID(query.pattern, query.language)}: no results`);
					return Promise.resolve(PATTERN_UNKNOWN);
				} else if (docs.length === 1) {
					log(`collectionLookup ${query.pattern}-${query.language}: result: ${docs[0].result}`);
					return Promise.resolve(docs[0]);
				} else {
					log(`collectionLookup unexpected multiple match: ${jsonStringify(docs)}`);
					return Promise.resolve(PATTERN_UNKNOWN);
				}
			},
			(e) => {
				log(`collectionLookup error: ${e}`);
				return Promise.resolve(PATTERN_UNKNOWN);
			}
		);
}
738113
@Override
    public <T> T query(MonetaryQuery<T> query) {
        Objects.requireNonNull(query);
        try {
            return query.queryFrom(this);
        } catch (MonetaryException | ArithmeticException e) {
            throw e;
        } catch (Exception e) {
            throw new MonetaryException("Query failed: " + query, e);
        }
    }
455868
@Override
    public MongodbQueryResult build(String query) throws IOException, ParserNotFoundException {
        DBObject result = (DBObject) super.parse(query);
        return new MongodbQueryResult(query, result);
    }
913126
@SuppressWarnings(UNCHECKED)
    protected List<E> list(Query query)
    {
        return new ArrayList<E>(query.list());
    }
1138021
public Deferred<SearchQuery> executeSearch(final SearchQuery query) {
    if (search == null) {
      throw new IllegalStateException(
          "Searching has not been enabled on this TSD");
    }

    return search.executeQuery(query);
  }
1105379
@Override
    public Iterator iterate()
    {
        EntityMetadata m = getEntityMetadata();
        Client client = persistenceDelegeator.getClient(m);
        return new ResultIterator((MongoDBClient) client, m,
                createMongoQuery(m, getKunderaQuery().getFilterClauseQueue()), getOrderByClause(m),
                getKeys(m, getKunderaQuery().getResult()), persistenceDelegeator,
                getFetchSize() != null ? getFetchSize() : this.maxResult);
    }
586170
public Api getQueryResult(String query) throws Exception {
    Api result = this.getActionResult("query", query, null, null);
    return result;
  }
91413
private ManageableCollection getCollectionByQuery(Class collectionClass, Class itemClass, Query query)
            throws ClassNotPersistenceCapableException, PersistenceBrokerException
    {
        if (log.isDebugEnabled()) log.debug("getCollectionByQuery (" + collectionClass + ", " + itemClass + ", " + query + ")");

        ClassDescriptor cld = pb.getClassDescriptor(itemClass);
        ManageableCollection result = null;
        OJBIterator iter = null;
        int fullSize = -1;
        int size = 0;

        final boolean isRetrievalTasksCreated = batchRetrieval && m_retrievalTasks == null;
        if (isRetrievalTasksCreated)
        {
            // Maps ReferenceDescriptors to HashSets of owners
            m_retrievalTasks = new HashMap();
        }

        // ==> enable materialization cache
        pb.getInternalCache().enableMaterializationCache();
        try
        {
            result = (ManageableCollection) collectionClass.newInstance();
            
            // now iterate over all elements and add them to the new collection
            // lifecycle events are disabled
            iter = pb.getIteratorFromQuery(query, cld);
            iter.disableLifeCycleEvents();

            // BRJ : get fullSizefor Query
            // to be removed when Query.fullSize is removed
            if (iter instanceof PagingIterator)
            {
                fullSize = iter.fullSize();
            }

            while (iter.hasNext())
            {
                Object candidate = iter.next();

                /**
                 * MBAIRD
                 * candidate CAN be null in the case of materializing from an iterator based
                 * on a query for a class that is mapped to a table that has other classes
                 * mapped to that table as well, but aren't extents.
                 */
                if (candidate != null)
                {
                    IndirectionHandler handler = ProxyHelper.getIndirectionHandler(candidate);

                    if ((handler != null) || itemClass.isAssignableFrom(candidate.getClass()))
                    {
                        result.ojbAdd(candidate);

                        // BRJ: count added objects
                        // to be removed when Query.fullSize is removed
                        size++;
                    }
                    else
                    {
                        //warn the user
                        log.warn("Candidate object ["+candidate
                                    +"] class ["+candidate.getClass().getName()
                                    +"] is not a subtype of ["+itemClass.getName()
                                    +"] or any type of proxy. NOT INCLUDED in result collection");
                    }
                    if (prefetchProxies && (handler != null)
                            && (cld.getProxyPrefetchingLimit() > 0)
                            && addRetrievalTask(candidate, this))
                    {
                        new PBMaterializationListener(candidate, m_retrievalTasks,
                                this, cld.getProxyPrefetchingLimit());
                    }
                }
            }

            if (isRetrievalTasksCreated)
            {
                // turn off auto prefetching for related proxies
                final Class saveClassToPrefetch = classToPrefetch;
                classToPrefetch = null;
                try
                {
                    performRetrievalTasks();
                }
                finally
                {
                    classToPrefetch = saveClassToPrefetch;
                }
            }

            // BRJ: fire LifeCycleEvents after execution of RetrievalTasks
            // to ensure objects are fully materialized
            Iterator resultIter = result.ojbIterator();
            while (resultIter.hasNext())
            {
                Object obj = resultIter.next();
                afterLookupEvent.setTarget(obj);
                pb.fireBrokerEvent(afterLookupEvent);
                afterLookupEvent.setTarget(null);
            }

            // ==> disable materialization cache
            pb.getInternalCache().disableMaterializationCache();
        }
        catch(RuntimeException e)
        {
            // ==> clear materialization cache
            pb.getInternalCache().doLocalClear();
            throw e;
        }
        catch (Exception ex)
        {
            // ==> clear materialization cache
            pb.getInternalCache().doLocalClear();
            log.error(ex);
            throw new PersistenceBrokerException(ex);
        }
        finally
        {
            if (iter != null)
            {
                iter.releaseDbResources();
            }
            if (isRetrievalTasksCreated)
            {
                m_retrievalTasks = null;
            }
        }

        // BRJ: store fullSize in Query to re-enable deprecated functionality
        // to be removed when Query.fullSize is removed
        if (fullSize < 0)
        {
            fullSize = size;	// use size of result
        }
        query.fullSize(fullSize);
        
        return result;
    }
1008221
@Override
    public IterableResult<Extension> search(ExtensionQuery query) throws SearchException
    {
        return RepositoryUtils.search(query, this.repositories);
    }
203215
public SearchResult<WorkflowSummary> search(@Nonnull String query) {
        return search(null, null, null, null, query);
    }
1171577
public SearchResult getSuggestions(StaplerRequest req, String query) {
        Set<String> paths = new HashSet<>();  // paths already added, to control duplicates
        SearchResultImpl r = new SearchResultImpl();
        int max = req.hasParameter("max") ? Integer.parseInt(req.getParameter("max")) : 100;
        SearchableModelObject smo = findClosestSearchableModelObject(req);
        for (SuggestedItem i : suggest(makeSuggestIndex(req), query, smo)) {
            if(r.size()>=max) {
                r.hasMoreResults = true;
                break;
            }
            if(paths.add(i.getPath()))
                r.add(i);
        }
        return r;
    }
1317053
def search(query)
      # get ranks
      query_vector = make_query_vector(query)
      ranks = @documents.map do |document|
        document_vector = make_vector(document)
        cosine_rank(query_vector, document_vector)
      end
    
      # now annotate records and return them
      @records.each_with_index do |record, i|
        # TODO: do this in a sensible way...
        record.instance_eval %{def rank; #{ranks[i]}; end}
      end
    
      # exclude 0 rank (no match) and sort by rank
      @records.reject { |r| r.rank == 0 }.sort { |a,b| b.rank <=> a.rank }
    end
375577
@Override
    public Iterable<T> findAll(@NonNull Sort sort) {
        Assert.notNull(sort, "sort of findAll should not be null");
        final DocumentQuery query = new DocumentQuery(Criteria.getInstance(CriteriaType.ALL)).with(sort);

        return operation.find(query, information.getJavaType(), information.getCollectionName());
    }
887497
public Query<S> query(Filter<S> filter, OrderingList<S> ordering, QueryHints hints)
        throws FetchException
    {
        filter = filter.bind();

        Map<OrderingList<S>, Query<S>> map;
        synchronized (mFilterToQuery) {
            map = mFilterToQuery.get(filter);
            if (map == null) {
                if (filter == null) {
                    throw new IllegalArgumentException("Query filter must not be null");
                }
                map = new SoftValuedHashMap(7);
                mFilterToQuery.put(filter, map);
            }
        }

        Query<S> query;
        synchronized (map) {
            query = map.get(ordering);
            if (query == null) {
                FilterValues<S> values = filter.initialFilterValues();
                if (values == null && filter.isClosed()) {
                    query = new EmptyQuery<S>(this, ordering);
                } else {
                    StandardQuery<S> standardQuery = createQuery(filter, values, ordering, hints);
                    if (!mLazySetExecutor) {
                        try {
                            standardQuery.setExecutor();
                        } catch (RepositoryException e) {
                            throw e.toFetchException();
                        }
                    }
                    query = standardQuery;
                }
                map.put(ordering, query);
            }
        }

        return query;
    }