Java Code Examples for com.mongodb.client.MongoCollection#find()

The following examples show how to use com.mongodb.client.MongoCollection#find() . 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: MongoIndraTranslator.java    From Indra with MIT License 6 votes vote down vote up
private Map<String, List<String>> doTranslate(Set<String> tokens) {
    MongoCollection<Document> lexColl = getLexCollection();
    FindIterable<Document> lexs = lexColl.find(Filters.in(TERM_FIELD, tokens));

    Map<String, List<String>> res = new HashMap<>();
    for (Document doc : lexs) {
        Document tr = (Document) doc.get(TRANSLATION_FIELD);

        if (tr != null) {
            tr.remove(NULL_VALUE);
            res.put(doc.getString(TERM_FIELD), getRelevantTranslations((Map) tr));
        }
    }

    return res;
}
 
Example 2
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 3
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 4
Source File: MongoCandidateSupplier.java    From baleen with Apache License 2.0 6 votes vote down vote up
@Override
public Collection<Candidate> getCandidates(EntityInformation<T> entityInformation) {

  Collection<Candidate> candidates = new HashSet<>();

  MongoCollection<Document> collection =
      mongoDatabase.getCollection(argumentsMap.get(PARAM_COLLECTION));

  Optional<Bson> buildQuery = buildQuery(entityInformation);
  if (buildQuery.isPresent()) {
    FindIterable<Document> documents = collection.find(buildQuery.get());

    for (Document document : documents) {
      Map<String, String> map = new MongoDocumentFlattener(document).flatten();
      String candidateID =
          document.get(argumentsMap.getOrDefault(PARAM_ID_FIELD, DEFAULT_MONGO_ID)).toString();
      String candidateName = document.get(argumentsMap.get(PARAM_SEARCH_FIELD)).toString();
      candidates.add(new DefaultCandidate(candidateID, candidateName, map));
    }
  }
  return candidates;
}
 
Example 5
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 6
Source File: RelationTypeFilter.java    From baleen with Apache License 2.0 6 votes vote down vote up
@Override
public void doInitialize(final UimaContext aContext) throws ResourceInitializationException {
  super.doInitialize(aContext);

  final MongoCollection<Document> dbCollection = mongo.getDB().getCollection(collection);

  for (Document o : dbCollection.find()) {
    RelationConstraint constraint =
        new RelationConstraint(
            (String) o.get(typeField),
            (String) o.get(subTypeField),
            (String) o.get(posField),
            (String) o.get(sourceField),
            (String) o.get(targetField));

    if (constraint.isValid()) {
      Set<RelationConstraint> set = constraints.get(constraint.getType());
      if (set == null) {
        set = new HashSet<>();
        constraints.put(constraint.getType().toLowerCase(), set);
      }
      set.add(constraint);
    }
  }
}
 
Example 7
Source File: MongoHelper.java    From MongoExplorer with MIT License 5 votes vote down vote up
public static List<MongoDocument> getPageOfDocuments(String collection, String queryText, int start, int take) {
	MongoCollection coll = Database.getCollection(collection);
	FindIterable main = (queryText == null) ? coll.find() : coll.find(Document.parse(queryText));
	FindIterable items = main.skip(start).limit(take);
	final ArrayList<MongoDocument> results = new ArrayList<>();

	items.forEach(new Block<Document>() {
		@Override
		public void apply(final Document document) {
			results.add(new MongoDocument(document.toJson()));
		}
	});

	return results;
}
 
Example 8
Source File: MongodbClientOpsDemo.java    From xian with Apache License 2.0 5 votes vote down vote up
private static void find() {
    MongoDatabase database = Mongo.getOrInitDefaultDatabase();
    MongoCollection<Person> collection = database.getCollection("dianping-collection", Person.class);
    // get it (since it's the only one in there since we dropped the rest earlier on)
    Person somebody = collection.find().first();
    System.out.println(somebody);

    System.out.println("");
    // now lets find every over 30
    for (Person person : collection.find(gt("age", 0))) {
        System.out.println(person);
    }
}
 
Example 9
Source File: CaseController.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@RequestMapping("/mongodb")
public String mongoDBCase() {
    try (MongoClient mongoClient = new MongoClient(host, port)) {
        MongoDatabase db = mongoClient.getDatabase("test-database");
        // CreateCollectionOperation
        db.createCollection("testCollection");

        MongoCollection<Document> collection = db.getCollection("testCollection");
        Document document = Document.parse("{id: 1, name: \"test\"}");
        // MixedBulkWriteOperation
        collection.insertOne(document);

        // FindOperation
        FindIterable<Document> findIterable = collection.find(eq("name", "org"));
        findIterable.first();

        // MixedBulkWriteOperation
        collection.updateOne(eq("name", "org"), BsonDocument.parse("{ $set : { \"name\": \"testA\"} }"));

        // FindOperation
        findIterable = collection.find(eq("name", "testA"));
        findIterable.first();

        // MixedBulkWriteOperation
        collection.deleteOne(eq("id", "1"));

        // DropDatabaseOperation
        mongoClient.dropDatabase("test-database");
    }
    return "success";
}
 
Example 10
Source File: DBusMongoClient.java    From DBus with Apache License 2.0 5 votes vote down vote up
private void obtainMajorShard() {
    MongoDatabase mdb = mongoClient.getDatabase("config");
    MongoCollection mongoCollection = mdb.getCollection("databases");
    FindIterable<Document> it = mongoCollection.find();
    for (Document doc : it) {
        // eg. { "_id" : "testdb", "primary" : "shard2", "partitioned" : true }
        logger.info("config.databases.find: {}", doc.toJson());
        dbMajorShardCache.put(doc.getString("_id"), doc.getString("primary"));
    }
}
 
Example 11
Source File: LegacyQuery.java    From morphia with Apache License 2.0 5 votes vote down vote up
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")));
        }

    }
}
 
Example 12
Source File: MongoDirectory.java    From lumongo with Apache License 2.0 5 votes vote down vote up
private void fetchInitialContents() throws MongoException, IOException {
	MongoCollection<Document> c = getFilesCollection();

	FindIterable<Document> cur = c.find();
	for (Document d : cur) {
		MongoFile mf = loadFileFromDBObject(d);
		nameToFileMap.put(mf.getFileName(), mf);
	}
}
 
Example 13
Source File: AssignTypeToInteraction.java    From baleen with Apache License 2.0 5 votes vote down vote up
@Override
public void doInitialize(final UimaContext aContext) throws ResourceInitializationException {
  super.doInitialize(aContext);

  ALGORITHM algo;
  try {
    algo = ALGORITHM.valueOf(algorithm);
  } catch (IllegalArgumentException iae) {
    getMonitor().warn("Algorithm {} doesn't exist, defaulting to ENGLISH", algorithm, iae);
    algo = ALGORITHM.ENGLISH;
  }
  stemmer = new SnowballStemmer(algo);

  final MongoCollection<Document> dbCollection = mongo.getDB().getCollection(collection);

  for (Document o : dbCollection.find()) {
    String type = (String) o.get(typeField);
    String subType = (String) o.get(subTypeField);
    String pos = (String) o.get(posField);
    List<?> values = (List<?>) o.get(valuesField);

    InteractionTypeDefinition definition = new InteractionTypeDefinition(type, subType, pos);

    values.stream()
        .filter(s -> s instanceof String)
        .forEach(
            s -> {
              String key = toKey(definition.getPos(), (String) s);
              definitions.put(key, definition);
            });
  }
}
 
Example 14
Source File: IdentifyInteractions.java    From baleen with Apache License 2.0 5 votes vote down vote up
/**
 * Read patterns from mongo.
 *
 * @return the list
 */
private List<PatternReference> readPatternsFromMongo() {
  // TODO: Ideally this would do something in a more streaming manner, as there are likely to
  // be lots of examples. Loading all patterns into memory might be prohibitive.

  final MongoCollection<Document> collection = mongo.getDB().getCollection(patternCollection);

  final List<PatternReference> patterns = new ArrayList<>((int) collection.count());

  for (Document doc : collection.find()) {
    @SuppressWarnings("unchecked")
    List<Document> list = doc.get("words", List.class);

    final List<Word> tokens =
        list.stream()
            .map(
                l -> {
                  final String pos = l.getString("pos");
                  String lemma = l.getString("lemma");

                  // Fall back to actual text if no lemma
                  if (lemma == null) {
                    lemma = l.getString("text");
                  }

                  return new Word(lemma.trim().toLowerCase(), WordNetUtils.toPos(pos));
                })
            .filter(w -> w.getPos() != null)
            .collect(Collectors.toList());

    final PatternReference pattern = new PatternReference(doc.get("_id").toString(), tokens);
    pattern.setSourceType(((Document) doc.get("source")).getString("type"));
    pattern.setTargetType(((Document) doc.get("target")).getString("type"));
    patterns.add(pattern);
  }

  return patterns;
}
 
Example 15
Source File: MDbMetaData.java    From birt with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Returns all fields' name and corresponding metadata found in the specified collection.
 * @param collectionName name of MongoDB collection (i.e. table)
 * @param searchLimit maximum number of documents, i.e. rows to search for available fields;
 *          a zero or negative value would adopt the default limit 
 * @param runtimeProps  an instance of QueryProperties containing the data set runtime property values;
 *          may be null to apply all default values in finding the available fields metadata
 * @return  the DocumentsMetaData object that contains the list of available field names and 
 *          corresponding metadata; 
 *          an empty list is returned if no available fields are found, or 
 *          if the specified collection does not exist
 * @throws OdaException
 */
public DocumentsMetaData getAvailableFields( String collectionName, 
        int searchLimit, QueryProperties runtimeProps )
    throws OdaException
{
    MongoCollection<Document> collection = getCollection( collectionName );
    if( collection == null && ! runtimeProps.hasRunCommand() )
    {
        if( runtimeProps.getOperationType() == CommandOperationType.RUN_DB_COMMAND &&
            runtimeProps.getOperationExpression().isEmpty() )
            throw new OdaException( 
                Messages.bind( Messages.mDbMetaData_missingCmdExprText, runtimeProps.getOperationType().displayName() ));
        else
            throw new OdaException( 
                Messages.bind( Messages.mDbMetaData_invalidCollectionName, collectionName ));
    }

    if( searchLimit <= 0 )  // no limit specified, applies meta data design-time default
        searchLimit = DEFAULT_META_DATA_SEARCH_LIMIT;
                    
    // handle optional command operation
    if( runtimeProps.hasValidCommandOperation() )
    {
        QueryModel.validateCommandSyntax( runtimeProps.getOperationType(), 
                            runtimeProps.getOperationExpression() );

        Iterable<Document> commandResults = null;
        if( runtimeProps.hasAggregateCommand() )
            commandResults = MDbOperation.callAggregateCmd( collection, runtimeProps );
        else if( runtimeProps.hasMapReduceCommand() )
        {
            commandResults  = MDbOperation.callMapReduceCmd( collection, runtimeProps );                
            // skip running $query on output collection in discovering metadata
        }
        else if( runtimeProps.hasRunCommand() )
            commandResults = MDbOperation.callDBCommand( m_connectedDB, runtimeProps );
        
        if( commandResults != null )
            return getMetaData( commandResults, searchLimit );
        return sm_emptyFields;
    }

    // run search query operation by default
    FindIterable<Document> rowsCursor = collection.find();

    if( searchLimit > 0 )
        rowsCursor.limit( searchLimit );
    
    QueryProperties mdCursorProps = runtimeProps != null ?
                        runtimeProps :
                        QueryProperties.defaultValues();
    MDbOperation.applyPropertiesToCursor( rowsCursor, mdCursorProps, false );        

    return getMetaData( rowsCursor );
}
 
Example 16
Source File: GetMongoRecord.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
    FlowFile input = null;

    if (context.hasIncomingConnection()) {
        input = session.get();
        if (input == null && context.hasNonLoopConnection()) {
            return;
        }
    }

    final String database = context.getProperty(DATABASE_NAME).evaluateAttributeExpressions(input).getValue();
    final String collection = context.getProperty(COLLECTION_NAME).evaluateAttributeExpressions(input).getValue();
    final String schemaName = context.getProperty(SCHEMA_NAME).evaluateAttributeExpressions(input).getValue();
    final Document query = getQuery(context, session, input);

    MongoCollection mongoCollection = clientService.getDatabase(database).getCollection(collection);

    FindIterable<Document> find = mongoCollection.find(query);
    if (context.getProperty(SORT).isSet()) {
        find = find.sort(Document.parse(context.getProperty(SORT).evaluateAttributeExpressions(input).getValue()));
    }
    if (context.getProperty(PROJECTION).isSet()) {
        find = find.projection(Document.parse(context.getProperty(PROJECTION).evaluateAttributeExpressions(input).getValue()));
    }
    if (context.getProperty(LIMIT).isSet()) {
        find = find.limit(context.getProperty(LIMIT).evaluateAttributeExpressions(input).asInteger());
    }

    MongoCursor<Document> cursor = find.iterator();

    FlowFile output = input != null ? session.create(input) : session.create();
    final FlowFile inputPtr = input;
    try {
        final Map<String, String> attributes = getAttributes(context, input, query, mongoCollection);
        try (OutputStream out = session.write(output)) {
            Map<String, String> attrs = inputPtr != null ? inputPtr.getAttributes() : new HashMap<String, String>(){{
                put("schema.name", schemaName);
            }};
            RecordSchema schema = writerFactory.getSchema(attrs, null);
            RecordSetWriter writer = writerFactory.createWriter(getLogger(), schema, out, attrs);
            long count = 0L;
            writer.beginRecordSet();
            while (cursor.hasNext()) {
                Document next = cursor.next();
                if (next.get("_id") instanceof ObjectId) {
                    next.put("_id", next.get("_id").toString());
                }
                Record record = new MapRecord(schema, next);
                writer.write(record);
                count++;
            }
            writer.finishRecordSet();
            writer.close();
            out.close();
            attributes.put("record.count", String.valueOf(count));
        } catch (SchemaNotFoundException e) {
            throw new RuntimeException(e);
        }


        output = session.putAllAttributes(output, attributes);

        session.getProvenanceReporter().fetch(output, getURI(context));
        session.transfer(output, REL_SUCCESS);
        if (input != null) {
            session.transfer(input, REL_ORIGINAL);
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        getLogger().error("Error writing record set from Mongo query.", ex);
        session.remove(output);
        if (input != null) {
            session.transfer(input, REL_FAILURE);
        }
    }
}
 
Example 17
Source File: MongoDbClient.java    From javase with MIT License 4 votes vote down vote up
public static void main( String args[] ) {
	
      try{
		
         // To connect to mongodb server
         MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
			
         // Now connect to your databases
         MongoDatabase db = mongoClient.getDatabase("test"); 
         //DB db = mongoClient.getDB( "test" );
         System.out.println("Connect to database successfully");
         //boolean auth = db.authenticate(myUserName, myPassword);
         //System.out.println("Authentication: "+auth);
		
         //DBCollection coll = db.createCollection("mycol", null);
         if (db.getCollection("mycol") != null) {
        	 db.getCollection("mycol").drop();
         }
         db.createCollection("mycol");
         
         System.out.println("Collection created successfully");
         
         // /*DBCollection*/ coll = db.getCollection("mycol");
         MongoCollection<Document> coll = db.getCollection("mycol");
         System.out.println("Collection mycol selected successfully");
			
//         BasicDBObject doc = new BasicDBObject("title", "MongoDB").
//            append("description", "database").
//            append("likes", 100).
//            append("url", "http://www.tutorialspoint.com/mongodb/").
//            append("by", "tutorials point");
         Document doc = new Document("title", "MongoDB").
               append("description", "database").
               append("likes", 100).
               append("url", "http://www.tutorialspoint.com/mongodb/").
               append("by", "tutorials point"); 
				
         //coll.insert(doc);
         coll.insertOne(doc);
         System.out.println("Document inserted successfully: " + doc.toJson());
         
         
         /*DBCollection*/ coll = db.getCollection("mycol");
         System.out.println("Collection mycol selected successfully");
			
         //DBCursor cursor = coll.find();
         FindIterable<Document> iterableFind = coll.find();
         MongoCursor<Document> cursor = iterableFind.iterator();
         int i = 1;
			
         while (cursor.hasNext()) { 
            System.out.println("Inserted Document: "+i); 
            System.out.println(cursor.next()); 
            i++;
         }
         
         mongoClient.close();
      }catch(Exception e){
         System.err.println( e.getClass().getName() + ": " + e.getMessage() );
      }
   }
 
Example 18
Source File: ClusterHelper.java    From lumongo with Apache License 2.0 4 votes vote down vote up
public Nodes getNodes() {

		MongoDatabase db = mongo.getDatabase(database);

		MongoCollection<Document> membershipCollection = db.getCollection(CLUSTER_MEMBERSHIP);

		FindIterable<Document> results = membershipCollection.find();

		Nodes nodes = new Nodes();

		for (Document object : results) {
			LocalNodeConfig lnc = LocalNodeConfig.fromDocument((Document) object.get(DATA));

			String serverAddress = (String) object.get(SERVER_ADDRESS);
			nodes.add(serverAddress, lnc);
		}

		return nodes;

	}
 
Example 19
Source File: GetMongo.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    final ComponentLog logger = getLogger();

    final Document query = context.getProperty(QUERY).isSet() ? Document.parse(context.getProperty(QUERY).getValue()) : null;
    final Document projection = context.getProperty(PROJECTION).isSet() ? Document.parse(context.getProperty(PROJECTION).getValue()) : null;
    final Document sort = context.getProperty(SORT).isSet() ? Document.parse(context.getProperty(SORT).getValue()) : null;

    final MongoCollection<Document> collection = getCollection(context);

    try {
        final FindIterable<Document> it = query != null ? collection.find(query) : collection.find();
        if (projection != null) {
            it.projection(projection);
        }
        if (sort != null) {
            it.sort(sort);
        }
        if (context.getProperty(LIMIT).isSet()) {
            it.limit(context.getProperty(LIMIT).asInteger());
        }
        if (context.getProperty(BATCH_SIZE).isSet()) {
            it.batchSize(context.getProperty(BATCH_SIZE).asInteger());
        }

        final MongoCursor<Document> cursor = it.iterator();
        try {
            FlowFile flowFile = null;
            while (cursor.hasNext()) {
                flowFile = session.create();
                flowFile = session.write(flowFile, new OutputStreamCallback() {
                    @Override
                    public void process(OutputStream out) throws IOException {
                        IOUtils.write(cursor.next().toJson(), out);
                    }
                });

                session.getProvenanceReporter().receive(flowFile, context.getProperty(URI).getValue());
                session.transfer(flowFile, REL_SUCCESS);
            }

            session.commit();

        } finally {
            cursor.close();
        }

    } catch (final RuntimeException e) {
        context.yield();
        session.rollback();
        logger.error("Failed to execute query {} due to {}", new Object[] { query, e }, e);
    }
}
 
Example 20
Source File: MongoSdkBase.java    From Mongodb-WeAdmin with Apache License 2.0 2 votes vote down vote up
/**
 * 查询 单条记录 返回 org.bson.Document  对象
 *
 * @param table  表连接
 * @return
 */
public  Document seleteOneDocument(MongoCollection table, Bson filter) {
    FindIterable<Document> result = table.find(filter);
    return result.first();
}