com.mongodb.client.FindIterable Java Examples

The following examples show how to use com.mongodb.client.FindIterable. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MongoTable.java    From Quicksql with MIT License 7 votes vote down vote up
/**
 * 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);
        }
    };
}
 
Example #2
Source File: PanacheQueryImpl.java    From quarkus with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example #3
Source File: QueryPrimer.java    From spring-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
@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
}
 
Example #4
Source File: QueryPrimer.java    From spring-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
@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
}
 
Example #5
Source File: ResourceUtilities.java    From EDDI with Apache License 2.0 6 votes vote down vote up
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;
            }
        });
    }
}
 
Example #6
Source File: MongoResourceStorage.java    From EDDI with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #7
Source File: MongoCompensableLock.java    From ByteTCC with GNU Lesser General Public License v3.0 6 votes vote down vote up
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;
	}
}
 
Example #8
Source File: MongoSdkBase.java    From Mongodb-WeAdmin with Apache License 2.0 6 votes vote down vote up
/**
 * 查询所有记录  代码控制返回结果数
 *
 * @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;
}
 
Example #9
Source File: QueryPrimer.java    From spring-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
@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
}
 
Example #10
Source File: MalletClassifierTrainer.java    From baleen with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #11
Source File: QueryPrimer.java    From spring-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
@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
}
 
Example #12
Source File: QueryPrimer.java    From spring-tutorial with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
@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
}
 
Example #13
Source File: MongoTemplateRecordConsumerTest.java    From baleen with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #14
Source File: MongoPcjDocuments.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #15
Source File: MongoImpl.java    From tephra with MIT License 6 votes vote down vote up
@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;
}
 
Example #16
Source File: FeatureDao.java    From XBDD with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #17
Source File: MDbOperation.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
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 );
 }
 
Example #18
Source File: MDbOperation.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
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 );
     }        
 }
 
Example #19
Source File: FeatureDao.java    From XBDD with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #20
Source File: MongoNotebookRepo.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
@Override
public void remove(String folderPath, AuthenticationInfo subject) throws IOException {
  LOG.debug("remove folder, folderPath: {}", folderPath);
  String[] pathArray = toPathArray(folderPath, true);

  try (AutoLock autoLock = lock.lockForWrite()) {
    String id = findFolder(pathArray);
    FindIterable<Document> iter = folders.find(eq(Fields.PID, id));
    for (Document node : iter) {
      String nodeId = node.getString(Fields.ID);
      Boolean isDir = node.getBoolean(Fields.IS_DIR);
      String nodeName = node.getString(Fields.NAME);

      if (isDir) {
        StringBuilder sb = new StringBuilder();
        for (String s : pathArray) {
          sb.append("/").append(s);
        }
        sb.append("/").append(nodeName);

        String nodePath = sb.toString();
        remove(nodePath, subject);
      } else {
        folders.deleteOne(eq(Fields.ID, nodeId));
        notes.deleteOne(eq(Fields.ID, nodeId));
      }

      folders.deleteOne(eq(Fields.ID, nodeId));
    }
  }
}
 
Example #21
Source File: MongoGeospatialLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenNearbyLocation_whenSearchNearby_thenFound() {
    Point currentLoc = new Point(new Position(-0.126821, 51.495885));
    FindIterable<Document> result = collection.find(Filters.near("location", currentLoc, 1000.0, 10.0));

    assertNotNull(result.first());
    assertEquals("Big Ben", result.first().get("name"));
}
 
Example #22
Source File: MaxEntClassifierTrainer.java    From baleen with Apache License 2.0 5 votes vote down vote up
private Iterator<Instance> getDocumentsFromMongoWithRandonLabelAssignement() {
  FindIterable<Document> find = documentsCollection.find();
  return FluentIterable.from(new MongoIterable(find))
      .transform(
          d -> {
            String data = d.getString(contentField);
            String name = d.getObjectId("_id").toHexString();
            return new Instance(data, null, name, null);
          })
      .iterator();
}
 
Example #23
Source File: QueryPerformTest.java    From spring-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
@Test
public void test01_queryAll() {
	FindIterable<Document> iterable = db.getCollection("tmp_collection").find();
	log.debug("tmp_collection总文档数: {}", db.getCollection("tmp_collection").count());
	iterable.forEach(new Block<Document>() {
		@Override
		public void apply(Document document) {
			log.debug(document.getString("itemid"));
		}
	});
	Assert.assertNotNull(iterable);
}
 
Example #24
Source File: ChronoGraph.java    From epcis with Apache License 2.0 5 votes vote down vote up
public ArrayList<CachedChronoVertex> getCachedChronoVertices(BsonArray filters, String sortKey, Boolean isDesc,
		Integer limit) {
	ArrayList<CachedChronoVertex> vList = new ArrayList<CachedChronoVertex>();
	// Merge All the queries with $and
	CachedChronoGraph g = new CachedChronoGraph();
	BsonDocument baseQuery = new BsonDocument();
	FindIterable<BsonDocument> cursor;
	if (filters.isEmpty() == false) {
		baseQuery.put("$and", filters);
		cursor = vertices.find(baseQuery);
	} else {
		cursor = vertices.find();
	}
	if (sortKey != null) {
		if (isDesc == null)
			cursor.sort(new BsonDocument(sortKey, new BsonInt32(-1)));
		else if (isDesc == true) {
			cursor.sort(new BsonDocument(sortKey, new BsonInt32(-1)));
		} else
			cursor.sort(new BsonDocument(sortKey, new BsonInt32(1)));
	}
	if (limit != null)
		cursor.limit(limit);

	MongoCursor<BsonDocument> iter = cursor.iterator();
	while (iter.hasNext()) {
		BsonDocument doc = iter.next();
		String vid = doc.remove("_id").asString().getValue();
		CachedChronoVertex v = g.getChronoVertex(vid);
		v.setProperties(doc);
		vList.add(v);
	}
	return vList;
}
 
Example #25
Source File: MorphiaQuery.java    From morphia with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("ConstantConditions")
private <E> MongoCursor<E> prepareCursor(final FindOptions findOptions, final MongoCollection<E> collection) {
    final Document query = toDocument();

    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);

    MongoCollection<E> updated = findOptions.prepare(collection);

    FindIterable<E> iterable = clientSession != null
                               ? updated.find(clientSession, query)
                               : updated.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")));
        }

    }
}
 
Example #26
Source File: DatabaseReader.java    From kafka-connect-mongodb with Apache License 2.0 5 votes vote down vote up
private FindIterable<Document> find(int page){
    final FindIterable<Document> documents = oplog
            .find(query)
            .sort(new Document("$natural", 1))
            .skip(page * batchSize)
            .limit(batchSize)
            .projection(Projections.include("ts", "op", "ns", "o"))
            .cursorType(CursorType.TailableAwait);
    return documents;
}
 
Example #27
Source File: MongoRepository.java    From javers with Apache License 2.0 5 votes vote down vote up
private MongoCursor<Document> getMongoSnapshotsCursor(Bson query, Optional<QueryParams> queryParams) {
    FindIterable<Document> findIterable = snapshotsCollection()
        .find(applyQueryParams(query, queryParams));

    if (coreConfiguration.getCommitIdGenerator() == CommitIdGenerator.SYNCHRONIZED_SEQUENCE) {
        findIterable.sort(new Document(COMMIT_ID, DESC));
    }
    else {
        findIterable.sort(new Document(COMMIT_DATE_INSTANT, DESC));
    }

    return applyQueryParams(findIterable, queryParams).iterator();
}
 
Example #28
Source File: FindOptions.java    From morphia with Apache License 2.0 5 votes vote down vote up
/**
 * @param iterable the iterable to use
 * @param mapper   the mapper to use
 * @param type     the result type
 * @param <T>      the result type
 * @return the iterable instance for the query results
 * @morphia.internal
 */
public <T> FindIterable<T> apply(final FindIterable<T> iterable, final Mapper mapper, final Class<?> type) {
    if (projection != null) {
        iterable.projection(projection.map(mapper, type));
    }

    iterable.batchSize(batchSize);
    iterable.collation(collation);
    iterable.comment(comment);
    if (cursorType != null) {
        iterable.cursorType(cursorType);
    }
    iterable.hint(hint);
    iterable.hintString(hintString);
    iterable.limit(limit);
    iterable.max(max);
    iterable.maxAwaitTime(maxAwaitTimeMS, TimeUnit.MILLISECONDS);
    iterable.maxTime(maxTimeMS, TimeUnit.MILLISECONDS);
    iterable.min(min);
    iterable.noCursorTimeout(noCursorTimeout);
    iterable.oplogReplay(oplogReplay);
    iterable.partial(partial);
    iterable.returnKey(returnKey);
    iterable.showRecordId(showRecordId);
    iterable.skip(skip);
    if (sort != null) {
        Document mapped = new Document();
        MappedClass mappedClass = mapper.getMappedClass(type);
        for (final Entry<String, Object> entry : sort.entrySet()) {
            Object value = entry.getValue();
            boolean metaScore = value instanceof Document && ((Document) value).get("$meta") != null;
            mapped.put(new PathTarget(mapper, mappedClass, entry.getKey(), !metaScore).translatedPath(), value);
        }
        iterable.sort(mapped);
    }
    return iterable;
}
 
Example #29
Source File: MongoGeospatialLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenNearbyLocation_whenSearchUsingIntersect_thenFound() {
    ArrayList<Position> positions = new ArrayList<Position>();
    positions.add(new Position(-0.1439, 51.4952));
    positions.add(new Position(-0.1346, 51.4978));
    positions.add(new Position(-0.2177, 51.5135));
    positions.add(new Position(-0.1439, 51.4952));
    Polygon geometry = new Polygon(positions);
    FindIterable<Document> result = collection.find(Filters.geoIntersects("location", geometry));

    assertNotNull(result.first());
    assertEquals("Hyde Park", result.first().get("name"));
}
 
Example #30
Source File: PrintMongDB.java    From Java-Data-Analysis with MIT License 5 votes vote down vote up
public static void main(String[] args) {
    MongoClient client = new MongoClient("localhost", 27017);
    MongoDatabase friends = client.getDatabase("friends");
    MongoCollection relatives = friends.getCollection("relatives");
    
    Bson bson = Sorts.ascending("fname");
    FindIterable<Document> docs = relatives.find().sort(bson);
    int num = 0;
    for (Document doc : docs) {
        String name = doc.getString("fname");
        String relation = doc.getString("relation");
        System.out.printf("%4d. %s, %s%n", ++num, name, relation);
    }
}