com.mongodb.client.MongoCollection Java Examples

The following examples show how to use com.mongodb.client.MongoCollection. 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: RenderDao.java    From render with GNU General Public License v2.0 6 votes vote down vote up
public void updateZForTiles(final StackId stackId,
                            final Double z,
                            final List<String> tileIds)
        throws IllegalArgumentException, IllegalStateException {

    MongoUtil.validateRequiredParameter("stackId", stackId);
    MongoUtil.validateRequiredParameter("z", z);
    MongoUtil.validateRequiredParameter("tileIds", tileIds);

    final MongoCollection<Document> tileCollection = getTileCollection(stackId);
    final Document query = new Document("tileId", new Document("$in", tileIds));
    final Document update = new Document("$set", new Document("z", z));

    final UpdateResult result = tileCollection.updateMany(query, update);

    final String shortQueryForLog = "{ 'tileId': { '$in': [ " + tileIds.size() + " tile ids ... ] } }";
    LOG.debug("updateZForTiles: updated {} tile specs with {}.update({},{})",
              result.getModifiedCount(), MongoUtil.fullName(tileCollection), shortQueryForLog, update.toJson());
}
 
Example #3
Source File: MongoOperations.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private static void persistOrUpdate(MongoCollection collection, List<Object> entities) {
    //this will be an ordered bulk: it's less performant than a unordered one but will fail at the first failed write
    List<WriteModel> bulk = new ArrayList<>();
    for (Object entity : entities) {
        //we transform the entity as a document first
        BsonDocument document = getBsonDocument(collection, entity);

        //then we get its id field and create a new Document with only this one that will be our replace query
        BsonValue id = document.get(ID);
        if (id == null) {
            //insert with autogenerated ID
            bulk.add(new InsertOneModel(entity));
        } else {
            //insert with user provided ID or update
            BsonDocument query = new BsonDocument().append(ID, id);
            bulk.add(new ReplaceOneModel(query, entity,
                    new ReplaceOptions().upsert(true)));
        }
    }

    collection.bulkWrite(bulk);
}
 
Example #4
Source File: ResourceDAO.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public int getResourceType(String key) throws OneM2MException {

		MongoCollection<Document> collection = context.getDatabaseManager()
				.getCollection(collectionName);
		Document doc = collection.find(new BasicDBObject(OneM2mUtil.isUri(key) ? URI_KEY : RESID_KEY, key)).first();

		if (doc == null) {
			throw new OneM2MException(RESPONSE_STATUS.NOT_FOUND,
					"resource not found(" + key + ")");
		}
		
		int resType = (int) doc.get(Naming.RESOURCETYPE_SN);
		if (resType == RESOURCE_TYPE.MGMT_OBJ.Value()){
			return (int) doc.get(Naming.MGMTDEFINITION_SN);
		}

		// return (int)doc.get("resourceType");
		return (int) doc.get(Naming.RESOURCETYPE_SN);

	}
 
Example #5
Source File: TagAssignmentDao.java    From XBDD with Apache License 2.0 6 votes vote down vote up
public void saveTagAssignment(final Coordinates coordinates, final SingleTagAssignment singleTagAssignment) {
	final MongoCollection<TagAssignments> tagAssignments = getTagAssignmentColletions();
	final CoordinatesDto coordinatesDto = CoordinatesMapper.mapCoordinates(coordinates);
	final Bson query = Filters.eq("coordinates", coordinatesDto);

	final TagAssignments savedAssignments = tagAssignments.find(query).first();

	if (savedAssignments == null) {
		final TagAssignments newAssignments = new TagAssignments();
		newAssignments.setCoordinates(coordinatesDto);
		newAssignments.setTags(Arrays.asList(singleTagAssignment));
		tagAssignments.insertOne(newAssignments);
	} else {
		savedAssignments.getTags().removeIf(single -> single.getTag().equals(singleTagAssignment.getTag()));
		savedAssignments.getTags().add(singleTagAssignment);
		tagAssignments.replaceOne(query, savedAssignments);
	}

}
 
Example #6
Source File: QueryConverterIT.java    From sql-to-mongo-db-query-converter with Apache License 2.0 6 votes vote down vote up
private static void loadRecords(int totalRecords, String dataset, MongoCollection mc) throws IOException {
	List<Document> documents = new ArrayList<>(totalRecords);
    try(InputStream inputStream = QueryConverterIT.class.getResourceAsStream("/" + dataset + ".json");
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream))) {

        String line;
        while ((line = bufferedReader.readLine())!=null) {
            documents.add(Document.parse(line));
        }
    }

    for (Iterator<List<WriteModel>> iterator = Iterables.partition(Lists.transform(documents, new Function<Document, WriteModel>() {
        @Override
        public WriteModel apply(Document document) {
            return new InsertOneModel(document);
        }
    }),10000).iterator(); iterator.hasNext();) {
        mc.bulkWrite(iterator.next());
    }
}
 
Example #7
Source File: MongoDBConfig.java    From datacollector with Apache License 2.0 6 votes vote down vote up
private MongoCollection createMongoCollection(
    Stage.Context context,
    List<Stage.ConfigIssue> issues,
    ReadPreference readPreference,
    WriteConcern writeConcern
) {
  MongoCollection mongoCollection = null;
  try {
    if (readPreference != null) {
      mongoCollection = mongoDatabase.getCollection(collection).withReadPreference(readPreference);
    } else if (writeConcern != null) {
      mongoCollection = mongoDatabase.getCollection(collection).withWriteConcern(writeConcern);
    }
  } catch (MongoClientException e) {
    issues.add(context.createConfigIssue(
        Groups.MONGODB.name(),
        MONGO_CONFIG_PREFIX + "collection",
        Errors.MONGODB_03,
        collection,
        e.toString()
    ));
  }
  return mongoCollection;
}
 
Example #8
Source File: ResourceDAO.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public int getResourceType(String key) throws OneM2MException {

		MongoCollection<Document> collection = context.getDatabaseManager()
				.getCollection(collectionName);
		Document doc = collection.find(new BasicDBObject(OneM2mUtil.isUri(key) ? URI_KEY : RESID_KEY, key)).first();

		if (doc == null) {
			throw new OneM2MException(RESPONSE_STATUS.NOT_FOUND,
					"resource not found(" + key + ")");
		}
		
		int resType = (int) doc.get(Naming.RESOURCETYPE_SN);
		if (resType == RESOURCE_TYPE.MGMT_OBJ.Value()){
			return (int) doc.get(Naming.MGMTDEFINITION_SN);
		}

		// return (int)doc.get("resourceType");
		return (int) doc.get(Naming.RESOURCETYPE_SN);

	}
 
Example #9
Source File: MongoDb4Connection.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
private static MongoCollection<Document> getOrCreateMongoCollection(final MongoDatabase database,
        final String collectionName, final boolean isCapped, final Integer sizeInBytes) {
    try {
        LOGGER.debug("Gettting collection '{}'...", collectionName);
        // throws IllegalArgumentException if collectionName is invalid
        final MongoCollection<Document> found = database.getCollection(collectionName);
        LOGGER.debug("Got collection {}", found);
        return found;
    } catch (final IllegalStateException e) {
        LOGGER.debug("Collection '{}' does not exist.", collectionName);
        final CreateCollectionOptions options = new CreateCollectionOptions().capped(isCapped)
                .sizeInBytes(sizeInBytes);
        LOGGER.debug("Creating collection '{}' with options {}...", collectionName, options);
        database.createCollection(collectionName, options);
        LOGGER.debug("Created collection.");
        final MongoCollection<Document> created = database.getCollection(collectionName);
        LOGGER.debug("Got created collection {}", created);
        return created;
    }

}
 
Example #10
Source File: ReNounRelationshipAnnotator.java    From baleen with Apache License 2.0 6 votes vote down vote up
@Override
protected Supplier<Stream<DependencyTreeMatcher>> createPatternsSupplier()
    throws DependencyParseException {

  return new Supplier<Stream<DependencyTreeMatcher>>() {

    MongoDatabase db = mongoResource.getDB();
    final MongoCollection<Document> coll = db.getCollection(patternsCollection);

    @Override
    public Stream<DependencyTreeMatcher> get() {
      return StreamSupport.stream(coll.find().spliterator(), false)
          .map(
              document -> {
                try {
                  return DependencyTreeMatcher.create(document.getString(patternField));
                } catch (DependencyParseException e) {
                  return null;
                }
              })
          .filter(Predicates.notNull());
    }
  };
}
 
Example #11
Source File: MongoSubscriptionTask.java    From epcis with Apache License 2.0 6 votes vote down vote up
private void updateInitialRecordTime(String subscriptionID, String initialRecordTime) {

		MongoCollection<BsonDocument> collection = Configuration.mongoDatabase.getCollection("Subscription",
				BsonDocument.class);

		BsonDocument subscription = collection.find(new BsonDocument("subscriptionID", new BsonString(subscriptionID)))
				.first();
		subscription.put("initialRecordTime", new BsonString(initialRecordTime));

		if (subscription != null) {
			collection.findOneAndReplace(new BsonDocument("subscriptionID", new BsonString(subscriptionID)),
					subscription);
		}
		Configuration.logger.log(Level.INFO,
				"InitialRecordTime of Subscription ID: " + subscriptionID + " is updated to DB. ");
	}
 
Example #12
Source File: StatsDao.java    From XBDD with Apache License 2.0 6 votes vote down vote up
public void updateStatsForFeatures(final Coordinates coordinates, final List<XbddFeature> features) {
	final MongoCollection<Stats> statsCollection = getStatsCollection();

	// product and version are redundant for search, but ensure they're populated if the upsert results in an insert.
	final String id = coordinates.getProduct() + "/" + coordinates.getVersionString() + "/" + coordinates.getBuild();
	statsCollection.deleteOne(Filters.eq(id));

	final Stats newStats = new Stats();
	newStats.setCoordinates(CoordinatesMapper.mapCoordinates(coordinates));
	newStats.setId(id);
	newStats.setSummary(getNewStatsSummary());

	for (final XbddFeature xbddFeature : features) {
		if (xbddFeature.getElements() != null) {
			for (final XbddScenario scenario : xbddFeature.getElements()) {
				final List<String> stepStatuses = FeatureMapper.getStepStatusStream(scenario).collect(Collectors.toList());
				final String status = StatusHelper.reduceStatuses(stepStatuses).getTextName();
				newStats.getSummary().replace(status, newStats.getSummary().get(status) + 1);
			}
		}
	}
	statsCollection.insertOne(newStats);
}
 
Example #13
Source File: ResourceDAO.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public HashMap<String, Object> getAttributes(String keyName,
		String keyValue, List<String> attrNames) throws OneM2MException {

	MongoCollection<Document> collection = context.getDatabaseManager()
			.getCollection(collectionName);
	Document doc = collection.find(new BasicDBObject(keyName, keyValue))
			.first();

	if (doc == null) {
		throw new OneM2MException(RESPONSE_STATUS.NOT_FOUND,
				"resource not found");
	}

	HashMap<String, Object> results = new HashMap<String, Object>();
	Iterator<String> it = attrNames.iterator();
	while (it.hasNext()) {
		String attr = it.next();
		results.put(attr, doc.get(attr));
	}

	return results;

}
 
Example #14
Source File: MongoMetadataDaoImpl.java    From eagle with Apache License 2.0 6 votes vote down vote up
private <T> List<T> list(MongoCollection<Document> collection, Class<T> clz) {
    List<T> result = new LinkedList<T>();
    collection.find().map(new Function<Document, T>() {
        @Override
        public T apply(Document t) {
            String json = t.toJson();
            try {
                return mapper.readValue(json, clz);
            } catch (IOException e) {
                LOG.error("deserialize config item failed!", e);
            }
            return null;
        }
    }).into(result);
    return result;
}
 
Example #15
Source File: MongoDBConnection.java    From nationalparks with Apache License 2.0 6 votes vote down vote up
/**
 * @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;
}
 
Example #16
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 #17
Source File: MongoWrapperDefaultHandler.java    From DBus with Apache License 2.0 6 votes vote down vote up
/**
 * 根据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;

}
 
Example #18
Source File: MongoStorage.java    From LuckPerms with MIT License 6 votes vote down vote up
@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;
}
 
Example #19
Source File: ResourceDAO.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public List<Document> getDocuments(String keyName, String keyValue,
		RESOURCE_TYPE resType, String sortKey, boolean asc, int limit) {

	ArrayList<Document> docList = new ArrayList<Document>();

	BasicDBObject query = new BasicDBObject(keyName, keyValue).append(
			RESTYPE_KEY, resType.Value());
	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;

}
 
Example #20
Source File: MongoFile.java    From lumongo with Apache License 2.0 6 votes vote down vote up
private MongoBlock fetchBlock(Integer blockNumber, boolean createIfNotExist) throws IOException {

		MongoCollection<Document> c = mongoDirectory.getBlocksCollection();

		Document query = new Document();
		query.put(MongoDirectory.FILE_NUMBER, fileNumber);
		query.put(MongoDirectory.BLOCK_NUMBER, blockNumber);

		Document result = c.find(query).first();

		byte[] bytes;
		if (result != null) {
			bytes = ((Binary) result.get(MongoDirectory.BYTES)).getData();
			return new MongoBlock(this, blockNumber, bytes);
		}

		if (createIfNotExist) {
			bytes = new byte[blockSize];
			MongoBlock mongoBlock = new MongoBlock(this, blockNumber, bytes);
			storeBlock(mongoBlock);
			return mongoBlock;
		}

		return null;

	}
 
Example #21
Source File: MongoCompensableLock.java    From ByteTCC with GNU Lesser General Public License v3.0 6 votes vote down vote up
private boolean takeOverTransactionInMongoDB(TransactionXid transactionXid, String source, String target) {
	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);

		Bson globalFilter = Filters.eq(CONSTANTS_FD_GLOBAL, instanceId);
		Bson instIdFilter = Filters.eq("identifier", source);

		Document document = new Document("$set", new Document("identifier", target));

		UpdateResult result = collection.updateOne(Filters.and(globalFilter, instIdFilter), document);
		return result.getMatchedCount() == 1;
	} catch (RuntimeException rex) {
		logger.error("Error occurred while locking transaction(gxid= {}).", instanceId, rex);
		return false;
	}
}
 
Example #22
Source File: ResourceDAO.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public HashMap<String, Object> getAttributes(String keyName,
		String keyValue, List<String> attrNames) throws OneM2MException {

	MongoCollection<Document> collection = context.getDatabaseManager()
			.getCollection(collectionName);
	Document doc = collection.find(new BasicDBObject(keyName, keyValue))
			.first();

	if (doc == null) {
		throw new OneM2MException(RESPONSE_STATUS.NOT_FOUND,
				"resource not found");
	}

	HashMap<String, Object> results = new HashMap<String, Object>();
	Iterator<String> it = attrNames.iterator();
	while (it.hasNext()) {
		String attr = it.next();
		results.put(attr, doc.get(attr));
	}

	return results;

}
 
Example #23
Source File: ReNounScoring.java    From baleen with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #24
Source File: RestSubscriptionDAO.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void delSubscription(String uri, String notificationUri) {
	
	MongoCollection<Document> collection = dbManager.getCollection(collectionName);
	Document seqDoc = getDocument(URI_KEY, uri);
	
	if(seqDoc != null) {
		collection.deleteOne(seqDoc);
	}
}
 
Example #25
Source File: ContentInstanceAnncDAO.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private int deleteOldestNExpired(String containerId, int size) {
		
		log.debug("deleteOldestNExpired containerId:{}, size:{}", containerId, size);
		MongoCollection<Document> collection = context.getDatabaseManager()
				.getCollection(collectionName);
		BasicDBList and = new BasicDBList();
		DeleteResult result;
		
		if (size >= 0) {
			and.clear();	
			and.add(new BasicDBObject(PARENTID_KEY, containerId));
			and.add(new BasicDBObject(RESTYPE_KEY, RESOURCE_TYPE.CONTENT_INST.Value()));
			
			MongoCursor<Document> cursor = collection.find(new BasicDBObject("$and", and))
											.sort(new BasicDBObject(CREATETIME_KEY, 1))
											.limit(size).iterator();
			
			int deletedCount = 0;
			if (cursor.hasNext()) {
				Document doc = cursor.next();
//				and.clear();
//				and.add(new BasicDBObject(PARENTID_KEY, containerId));
//				and.add(new BasicDBObject(RESTYPE_KEY, RESOURCE_TYPE.CONTENT_INST.Value()));
//				and.add(new BasicDBObject(CREATETIME_KEY, new BasicDBObject("$lt", doc.get(CREATETIME_KEY))));
//				
				result = collection.deleteOne(new BasicDBObject(RESID_KEY, doc.get(RESID_KEY)));
	
				deletedCount += result.getDeletedCount();
			}
			log.debug("Deleted oldest contentInstance:{}", deletedCount);
			return deletedCount;
		}
		return 0;
		
	}
 
Example #26
Source File: TransformationQueryEmulationCode.java    From epcis with Apache License 2.0 5 votes vote down vote up
public void func1(final MongoCollection collection, final Object starts, final boolean setParallel,
		final boolean setPathEnabled, final Class elementClass) {

	currentPath = new HashMap<Object, Object>();

	if (starts instanceof ChronoGraph || starts instanceof ChronoVertex || starts instanceof ChronoEdge
			|| starts instanceof VertexEvent || starts instanceof EdgeEvent || starts instanceof EPCTime) {

		HashSet set = new HashSet();
		set.add(starts);
		if (setParallel == true)
			stream = set.parallelStream();
		else
			stream = set.stream();
		this.elementClass = starts.getClass();

		if (setPathEnabled) {
			HashSet initPathSet = new HashSet();
			List list = new ArrayList();
			list.add(starts);
			initPathSet.add(list);
			currentPath.put(starts, initPathSet);
		}
	}
	stepList = new ArrayList<Step>();
	stepIndex = new HashMap<String, Integer>();
	this.isPathEnabled = setPathEnabled;
	this.isParallel = setParallel;
	this.loopCount = 0;
	listElementClass = null;
	this.collection = collection;
}
 
Example #27
Source File: MongoMasterConnector.java    From syncer with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private MongoCursor<Document> getReplicaCursor(MongoClient client, Document query) {
  MongoDatabase db = client.getDatabase(LOCAL);
  MongoCollection<Document> coll = db.getCollection(OPLOG_RS);

  return coll.find(query)
      .cursorType(CursorType.TailableAwait)
      .oplogReplay(true)
      .iterator();
}
 
Example #28
Source File: AfterConvertCallbacksBenchmark.java    From spring-data-dev-tools with Apache License 2.0 5 votes vote down vote up
@Setup
public void setUp() {

	MongoClient client = mock(MongoClient.class);
	MongoDatabase db = mock(MongoDatabase.class);
	MongoCollection<Document> collection = mock(MongoCollection.class);

	when(client.getDatabase(anyString())).thenReturn(db);
	when(db.getCollection(anyString(), eq(Document.class))).thenReturn(collection);

	MongoDatabaseFactory factory = new SimpleMongoClientDatabaseFactory(client, "mock-database");

	templateWithoutContext = new MongoTemplate(factory);

	templateWithEmptyContext = new MongoTemplate(factory);
	StaticApplicationContext empty = new StaticApplicationContext();
	empty.refresh();
	templateWithEmptyContext.setApplicationContext(empty);

	templateWithContext = new MongoTemplate(factory);
	templateWithContext.setApplicationContext(new AnnotationConfigApplicationContext(EntityCallbackConfig.class));

	source = new Person();
	source.id = "luke-skywalker";
	source.firstname = "luke";
	source.lastname = "skywalker";

	source.address = new Address();
	source.address.street = "melenium falcon 1";
	source.address.city = "deathstar";
}
 
Example #29
Source File: IndexHelperTest.java    From morphia with Apache License 2.0 5 votes vote down vote up
@Test
public void indexPartialFilters() {
    MongoCollection<Document> collection = getDatabase().getCollection("indexes");
    MappedClass mappedClass = getMapper().getMappedClass(IndexedClass.class);

    Index index = new IndexBuilder()
        .fields(new FieldBuilder().value("text"))
        .options(new IndexOptionsBuilder()
                     .partialFilter("{ name : { $gt : 13 } }"));

    indexHelper.createIndex(collection, mappedClass, index);
    findPartialIndex(Document.parse(index.options().partialFilter()));
}
 
Example #30
Source File: IndexHelperTest.java    From morphia with Apache License 2.0 5 votes vote down vote up
@Test
public void indexedPartialFilters() {
    MongoCollection<Document> collection = getDatabase().getCollection("indexes");
    MappedClass mappedClass = getMapper().getMappedClass(IndexedClass.class);

    Indexed indexed = new IndexedBuilder()
        .options(new IndexOptionsBuilder()
                     .partialFilter("{ name : { $gt : 13 } }"));

    indexHelper.createIndex(collection, mappedClass, indexHelper.convert(indexed, "text"));
    findPartialIndex(Document.parse(indexed.options().partialFilter()));
}