Java Code Examples for org.bson.Document#size()

The following examples show how to use org.bson.Document#size() . 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: PrimitiveArray.java    From Prism with MIT License 8 votes vote down vote up
public static PrimitiveArray of(Document document) {
    if (document.size() != 2 || !(document.containsKey("key") && document.containsKey("value"))) {
        return null;
    }

    if (!(document.get("key") instanceof String)) {
        return null;
    }

    String key = document.getString("key");
    if (!StringUtils.equalsAny(key, BYTE_ARRAY_ID, INT_ARRAY_ID, LONG_ARRAY_ID)) {
        return null;
    }

    List<Number> value = document.getList("value", Number.class);
    if (value == null) {
        return null;
    }

    return new PrimitiveArray(key, value);
}
 
Example 2
Source File: MongoDBQueryTool.java    From datax-web with MIT License 6 votes vote down vote up
/**
 * 通过CollectionName查询列
 *
 * @param collectionName
 * @return
 */
public List<String> getColumns(String collectionName) {
    MongoCollection<Document> collection = collections.getCollection(collectionName);
    Document document = collection.find(new BasicDBObject()).first();
    List<String> list = new ArrayList<>();
    if (null == document || document.size() <= 0) {
        return list;
    }
    document.forEach((k, v) -> {
        if (null != v) {
            String type = v.getClass().getSimpleName();
            list.add(k + ":" + type);
        }
  /*if ("Document".equals(type)) {
    ((Document) v).forEach((k1, v1) -> {
      String simpleName = v1.getClass().getSimpleName();
    });
  } */

    });
    return list;
}
 
Example 3
Source File: GridFSITTestBase.java    From nifi with Apache License 2.0 6 votes vote down vote up
public boolean fileHasProperties(String name, String bucketName, Map<String, String> attrs) {
    GridFSBucket bucket = GridFSBuckets.create(client.getDatabase(DB), bucketName);
    MongoCursor it = bucket.find(Document.parse(String.format("{ \"filename\": \"%s\" }", name))).iterator();
    boolean retVal = false;

    if (it.hasNext()) {
        GridFSFile file = (GridFSFile)it.next();
        Document metadata = file.getMetadata();
        if (metadata != null && metadata.size() == attrs.size()) {
            retVal = true;
            for (Map.Entry<String, Object> entry : metadata.entrySet()) {
                Object val = attrs.get(entry.getKey());
                if (val == null || !entry.getValue().equals(val)) {
                    retVal = false;
                    break;
                }
            }
        }
    }

    it.close();

    return retVal;
}
 
Example 4
Source File: MongoDBClient.java    From redtorch with MIT License 5 votes vote down vote up
/**
 * 更新
 * 
 * @param dbName
 * @param collectionName
 * @param filter
 * @param document
 * @return
 */
public boolean updateOne(String dbName, String collectionName, Document filter, Document document) {
	if (filter != null && filter.size() > 0 && document != null) {
		UpdateResult result = mongoClient.getDatabase(dbName).getCollection(collectionName)
				.updateOne(new Document(filter), new Document("$set", new Document(document)));
		long modifiedCount = result.getModifiedCount();
		return modifiedCount > 0 ? true : false;
	}

	return false;
}
 
Example 5
Source File: MongoCompensableLogger.java    From ByteTCC with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void createTransactionsGlobalTxKeyIndexIfNecessary() {
	String databaseName = CommonUtils.getApplication(this.endpoint).replaceAll("\\W", "_");
	MongoDatabase database = this.mongoClient.getDatabase(databaseName);
	MongoCollection<Document> transactions = database.getCollection(CONSTANTS_TB_TRANSACTIONS);
	ListIndexesIterable<Document> transactionIndexList = transactions.listIndexes();
	boolean transactionIndexExists = false;
	MongoCursor<Document> transactionCursor = null;
	try {
		transactionCursor = transactionIndexList.iterator();
		while (transactionIndexExists == false && transactionCursor.hasNext()) {
			Document document = transactionCursor.next();
			Boolean unique = document.getBoolean("unique");
			Document key = (Document) document.get("key");

			boolean globalExists = key.containsKey(CONSTANTS_FD_GLOBAL);
			boolean lengthEquals = key.size() == 1;
			transactionIndexExists = lengthEquals && globalExists;

			if (transactionIndexExists && (unique == null || unique == false)) {
				throw new IllegalStateException();
			}
		}
	} finally {
		IOUtils.closeQuietly(transactionCursor);
	}

	if (transactionIndexExists == false) {
		Document index = new Document(CONSTANTS_FD_GLOBAL, 1);
		transactions.createIndex(index, new IndexOptions().unique(true));
	}
}
 
Example 6
Source File: MongoCompensableLock.java    From ByteTCC with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void createLocksIndexIfNecessary() {
	String databaseName = CommonUtils.getApplication(this.endpoint).replaceAll("\\W", "_");
	MongoDatabase database = this.mongoClient.getDatabase(databaseName);
	MongoCollection<Document> locks = database.getCollection(CONSTANTS_TB_LOCKS);
	ListIndexesIterable<Document> lockIndexList = locks.listIndexes();
	boolean transactionIndexExists = false;
	MongoCursor<Document> lockCursor = null;
	try {
		lockCursor = lockIndexList.iterator();
		while (transactionIndexExists == false && lockCursor.hasNext()) {
			Document document = lockCursor.next();
			Boolean unique = document.getBoolean("unique");
			Document key = (Document) document.get("key");

			boolean globalExists = key.containsKey(CONSTANTS_FD_GLOBAL);
			boolean lengthEquals = key.size() == 1;
			transactionIndexExists = lengthEquals && globalExists;

			if (transactionIndexExists && (unique == null || unique == false)) {
				throw new IllegalStateException();
			}
		}
	} finally {
		IOUtils.closeQuietly(lockCursor);
	}

	if (transactionIndexExists == false) {
		Document index = new Document(CONSTANTS_FD_GLOBAL, 1);
		locks.createIndex(index, new IndexOptions().unique(true));
	}
}
 
Example 7
Source File: QueryConverter.java    From sql-to-mongo-db-query-converter with Apache License 2.0 4 votes vote down vote up
/**
 * Build a mongo shell statement with the code to run the specified query.
 * @param outputStream the {@link java.io.OutputStream} to write the data to
 * @throws IOException when there is an issue writing to the {@link java.io.OutputStream}
 */
public void write(OutputStream outputStream) throws IOException {
    MongoDBQueryHolder mongoDBQueryHolder = getMongoQuery();
    boolean isFindQuery = false;
    if (mongoDBQueryHolder.isDistinct()) {
        IOUtils.write("db." + mongoDBQueryHolder.getCollection() + ".distinct(", outputStream);
        IOUtils.write("\""+getDistinctFieldName(mongoDBQueryHolder) + "\"", outputStream);
        IOUtils.write(" , ", outputStream);
        IOUtils.write(prettyPrintJson(mongoDBQueryHolder.getQuery().toJson(relaxed)), outputStream);
    } else if (sqlCommandInfoHolder.isCountAll() && !isAggregate(mongoDBQueryHolder)) {
        IOUtils.write("db." + mongoDBQueryHolder.getCollection() + ".count(", outputStream);
        IOUtils.write(prettyPrintJson(mongoDBQueryHolder.getQuery().toJson(relaxed)), outputStream);
    } else if (isAggregate(mongoDBQueryHolder)) {
    	IOUtils.write("db." + mongoDBQueryHolder.getCollection() + ".aggregate(", outputStream);
        IOUtils.write("[", outputStream);
        
        IOUtils.write(Joiner.on(",").join(Lists.transform(generateAggSteps(mongoDBQueryHolder,sqlCommandInfoHolder), new com.google.common.base.Function<Document, String>() {
            @Override
            public String apply(Document document) {
                return prettyPrintJson(document.toJson(relaxed));
            }
        })),outputStream);
        IOUtils.write("]", outputStream);

        Document options = new Document();
        if (aggregationAllowDiskUse != null) {
            options.put("allowDiskUse", aggregationAllowDiskUse);
        }

        if (aggregationBatchSize != null) {
            options.put("cursor",new Document("batchSize", aggregationBatchSize));
        }

        if (options.size() > 0) {
            IOUtils.write(",",outputStream);
            IOUtils.write(prettyPrintJson(options.toJson(relaxed)),outputStream);
        }



    } else {
    	if(sqlCommandInfoHolder.getSqlCommandType() == SQLCommandType.SELECT) {
     	isFindQuery = true;
         IOUtils.write("db." + mongoDBQueryHolder.getCollection() + ".find(", outputStream);
    	}
    	else if(sqlCommandInfoHolder.getSqlCommandType() == SQLCommandType.DELETE){
    		IOUtils.write("db." + mongoDBQueryHolder.getCollection() + ".remove(", outputStream);
    	}
        IOUtils.write(prettyPrintJson(mongoDBQueryHolder.getQuery().toJson(relaxed)), outputStream);
        if (mongoDBQueryHolder.getProjection() != null && mongoDBQueryHolder.getProjection().size() > 0 && sqlCommandInfoHolder.getSqlCommandType() == SQLCommandType.SELECT) {
            IOUtils.write(" , ", outputStream);
            IOUtils.write(prettyPrintJson(mongoDBQueryHolder.getProjection().toJson(relaxed)), outputStream);
        }
    }
    IOUtils.write(")", outputStream);

    if(isFindQuery) {
    	if (mongoDBQueryHolder.getSort()!=null && mongoDBQueryHolder.getSort().size() > 0) {
            IOUtils.write(".sort(", outputStream);
            IOUtils.write(prettyPrintJson(mongoDBQueryHolder.getSort().toJson(relaxed)), outputStream);
            IOUtils.write(")", outputStream);
        }
        
        if (mongoDBQueryHolder.getOffset()!=-1) {
            IOUtils.write(".skip(", outputStream);
            IOUtils.write(mongoDBQueryHolder.getOffset()+"", outputStream);
            IOUtils.write(")", outputStream);
        }

        if (mongoDBQueryHolder.getLimit()!=-1) {
            IOUtils.write(".limit(", outputStream);
            IOUtils.write(mongoDBQueryHolder.getLimit()+"", outputStream);
            IOUtils.write(")", outputStream);
        }
    }
}