org.bson.conversions.Bson Java Examples
The following examples show how to use
org.bson.conversions.Bson.
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 |
/** * 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: MongoClientImpl.java From vertx-mongo-client with Apache License 2.0 | 6 votes |
private AggregatePublisher<JsonObject> doAggregate(final String collection, final JsonArray pipeline, final AggregateOptions aggregateOptions) { requireNonNull(collection, "collection cannot be null"); requireNonNull(pipeline, "pipeline cannot be null"); requireNonNull(aggregateOptions, "aggregateOptions cannot be null"); final MongoCollection<JsonObject> coll = getCollection(collection); final List<Bson> bpipeline = new ArrayList<>(pipeline.size()); pipeline.getList().forEach(entry -> bpipeline.add(wrap(JsonObject.mapFrom(entry)))); AggregatePublisher<JsonObject> aggregate = coll.aggregate(bpipeline, JsonObject.class); if (aggregateOptions.getBatchSize() != -1) { aggregate.batchSize(aggregateOptions.getBatchSize()); } if (aggregateOptions.getMaxTime() > 0) { aggregate.maxTime(aggregateOptions.getMaxTime(), TimeUnit.MILLISECONDS); } if (aggregateOptions.getAllowDiskUse() != null) { aggregate.allowDiskUse(aggregateOptions.getAllowDiskUse()); } return aggregate; }
Example #3
Source File: AbstractMongoRepository.java From edison-microservice with Apache License 2.0 | 6 votes |
/** * Updates the document if the document's ETAG is matching the given etag (conditional put). * <p> * Using this method requires that the document contains an "etag" field that is updated if * the document is changed. * </p> * * @param value the new value * @param eTag the etag used for conditional update * @param maxTime max time for the update * @param timeUnit the time unit for the maxTime value * @return {@link UpdateIfMatchResult} */ public UpdateIfMatchResult updateIfMatch(final V value, final String eTag, final long maxTime, final TimeUnit timeUnit) { final K key = keyOf(value); if (key != null) { final Bson query = and(eq(AbstractMongoRepository.ID, key), eq(ETAG, eTag)); final Document updatedETaggable = collectionWithWriteTimeout(maxTime, timeUnit).findOneAndReplace(query, encode(value), new FindOneAndReplaceOptions().returnDocument(AFTER)); if (isNull(updatedETaggable)) { final boolean documentExists = collection() .countDocuments(eq(AbstractMongoRepository.ID, key), new CountOptions().maxTime(maxTime, timeUnit)) != 0; if (documentExists) { return CONCURRENTLY_MODIFIED; } return NOT_FOUND; } return OK; } else { throw new IllegalArgumentException("Key must not be null"); } }
Example #4
Source File: MongoDao.java From elepy with Apache License 2.0 | 6 votes |
private Bson createIndexField(String property) { final var split = property.split(":"); //Ensures property exists schema.getProperty(split[0]); if (split.length == 1) { return Indexes.ascending(property); } try { final var i = Integer.parseInt(split[1]); return new BasicDBObject(property, i); } catch (NumberFormatException e) { throw new ElepyConfigException(String.format("%s is not a valid integer", split[1]), e); } }
Example #5
Source File: WriteContext.java From pinpoint with Apache License 2.0 | 6 votes |
public String parse(Object arg) { if (arg instanceof Bson) { writeValue(arg); } else if (arg instanceof List) { if (((List) arg).get(0) instanceof Bson) { bsonWriter.writeStartDocument(); bsonWriter.writeName("bsons"); writeValue(arg); bsonWriter.writeEndDocument(); } else { logger.debug(UNTRACED); return UNTRACED; } } else { logger.debug(UNTRACED); return UNTRACED; } return writer.toString(); }
Example #6
Source File: MongoDbAccessor.java From mongodb-slow-operations-profiler with GNU Affero General Public License v3.0 | 6 votes |
public Document runCommand(String dbName, DBObject cmd) throws IllegalStateException { if(dbName != null && !dbName.isEmpty()) { long start = System.currentTimeMillis(); Document result = new Document(); try { result = getMongoDatabase(dbName).runCommand((Bson) cmd, isSecondaryReadPreferred ? ReadPreference.secondaryPreferred() : ReadPreference.primaryPreferred()); }catch (Throwable e){ LOG.warn("runCommand failed {} on {}/{}", new Object[]{cmd.toString(), serverAddresses, dbName}); throw e; } long end = System.currentTimeMillis(); LOG.info("runCommand {} execTime in ms: {} on {}/{}", new Object[]{cmd.toString(), (end-start), serverAddresses, dbName}); return result; } throw new IllegalStateException("Database not initialized"); }
Example #7
Source File: BsonUtil.java From ditto with Eclipse Public License 2.0 | 5 votes |
/** * Pretty-prints a Bson object. * * @param bson Bson object to be printed, may be {@code null}. * @return String representation of the Bson. */ public static String prettyPrint(@Nullable final Bson bson) { if (bson == null) { return NULL_STRING; } return toBsonDocument(bson).toJson(); }
Example #8
Source File: InsertMongoDB.java From Java-Data-Analysis with MIT License | 5 votes |
public static void printCollection(MongoCollection collection) { Bson bson = Sorts.ascending("fname"); FindIterable<Document> docs = collection.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); } }
Example #9
Source File: MongoCollectionImpl.java From mongo-java-driver-rx with Apache License 2.0 | 5 votes |
@Override public Observable<TDocument> findOneAndReplace(final Bson filter, final TDocument replacement, final FindOneAndReplaceOptions options) { return RxObservables.create(Observables.observe(new Block<SingleResultCallback<TDocument>>() { @Override public void apply(final SingleResultCallback<TDocument> callback) { wrapped.findOneAndReplace(filter, replacement, options, callback); } }), observableAdapter); }
Example #10
Source File: Operations.java From stitch-android-sdk with Apache License 2.0 | 5 votes |
private List<BsonDocument> toBsonDocumentList(final List<? extends Bson> bsonList) { if (bsonList == null) { return null; } final List<BsonDocument> bsonDocumentList = new ArrayList<>(bsonList.size()); for (final Bson cur : bsonList) { bsonDocumentList.add(toBsonDocument(cur, documentClass, codecRegistry)); } return bsonDocumentList; }
Example #11
Source File: MongoDBOplogSource.java From datacollector with Apache License 2.0 | 5 votes |
private void prepareCursor(int timestampSeconds, int ordinal, List<OplogOpType> filterOplogTypes, int batchSize) { LOG.debug("Getting new cursor with offset - TimeStampInSeconds:'{}', Ordinal : '{}' and Batch Size : '{}'",timestampSeconds, ordinal, batchSize); FindIterable<Document> mongoCursorIterable = mongoCollection .find() //As the collection is a capped collection we use Tailable cursor which will return results in natural order in this case //based on ts timestamp field. //Tailable Await does not return and blocks, so we are using tailable. .cursorType(CursorType.Tailable) .batchSize(batchSize); List<Bson> andFilters = new ArrayList<>(); //Only filter if we already have saved/initial offset specified or else both time_t and ordinal will not be -1. if (timestampSeconds > 0 && ordinal >= 0) { andFilters.add(Filters.gt(TIMESTAMP_FIELD, new BsonTimestamp(timestampSeconds, ordinal))); } if (!filterOplogTypes.isEmpty()) { List<Bson> oplogOptypeFilters = new ArrayList<>(); Set<OplogOpType> oplogOpTypesSet = new HashSet<>(); for (OplogOpType filterOplogopType : filterOplogTypes) { if (oplogOpTypesSet.add(filterOplogopType)) { oplogOptypeFilters.add(Filters.eq(OP_TYPE_FIELD, filterOplogopType.getOp())); } } //Add an or filter for filtered Or Types andFilters.add(Filters.or(oplogOptypeFilters)); } //Finally and timestamp with oplog filters if (!andFilters.isEmpty()) { mongoCursorIterable = mongoCursorIterable.filter(Filters.and(andFilters)); } cursor = mongoCursorIterable.iterator(); }
Example #12
Source File: MongoDatabaseImpl.java From mongo-java-driver-reactivestreams with Apache License 2.0 | 5 votes |
@Override public <TResult> Publisher<TResult> runCommand(final ClientSession clientSession, final Bson command, final Class<TResult> clazz) { return new ObservableToPublisher<TResult>(com.mongodb.async.client.Observables.observe( new Block<com.mongodb.async.SingleResultCallback<TResult>>() { @Override public void apply(final com.mongodb.async.SingleResultCallback<TResult> callback) { wrapped.runCommand(clientSession.getWrapped(), command, clazz, callback); } })); }
Example #13
Source File: QueryBuilder.java From elepy with Apache License 2.0 | 5 votes |
private Bson booleanGroup(BooleanGroup expression) { final var groupExpressions = expression.getExpressions().stream().map(this::expression).collect(Collectors.toList()); if (expression.getOperator().equals(BooleanGroup.BooleanOperator.AND)) { return Filters.and(groupExpressions); } else { return Filters.or(groupExpressions); } }
Example #14
Source File: MongoClientImpl.java From vertx-mongo-client with Apache License 2.0 | 5 votes |
@Override public Future<@Nullable MongoClientDeleteResult> removeDocumentWithOptions(String collection, JsonObject query, @Nullable WriteOption writeOption) { requireNonNull(collection, "collection cannot be null"); requireNonNull(query, "query cannot be null"); MongoCollection<JsonObject> coll = getCollection(collection, writeOption); Bson bquery = wrap(encodeKeyWhenUseObjectId(query)); Promise<DeleteResult> promise = vertx.promise(); coll.deleteOne(bquery).subscribe(new SingleResultSubscriber<>(promise)); return promise.future().map(Utils::toMongoClientDeleteResult); }
Example #15
Source File: MongoTransactionServiceImpl.java From nuls-v2 with MIT License | 5 votes |
@Override public void deleteUnConfirmTx(int chainId, String txHash) { Bson filter1 = Filters.eq("_id", txHash); Bson filter2 = Filters.eq("txHash", txHash); mongoDBService.delete(TX_UNCONFIRM_TABLE + chainId, filter1); mongoDBService.delete(TX_UNCONFIRM_RELATION_TABLE + chainId, filter2); txUnConfirmHashSet.remove(txHash); }
Example #16
Source File: MongoCollectionImpl.java From mongo-java-driver-reactivestreams with Apache License 2.0 | 5 votes |
@Override public Publisher<DeleteResult> deleteMany(final Bson filter, final DeleteOptions options) { return new ObservableToPublisher<DeleteResult>(com.mongodb.async.client.Observables.observe( new Block<com.mongodb.async.SingleResultCallback<DeleteResult>>() { @Override public void apply(final com.mongodb.async.SingleResultCallback<DeleteResult> callback) { wrapped.deleteMany(filter, options, callback); } })); }
Example #17
Source File: MongoDepositServiceImpl.java From nuls-v2 with MIT License | 5 votes |
public List<DepositInfo> getDepositListByAgentHash(int chainId, String hash) { List<DepositInfo> depositInfos = new ArrayList<>(); Bson bson = Filters.and(Filters.eq("agentHash", hash), Filters.eq("deleteKey", null)); List<Document> documentList = mongoDBService.query(DEPOSIT_TABLE + chainId, bson); if (documentList == null && documentList.isEmpty()) { return depositInfos; } for (Document document : documentList) { DepositInfo depositInfo = DocumentTransferTool.toInfo(document, "key", DepositInfo.class); depositInfos.add(depositInfo); } return depositInfos; }
Example #18
Source File: ChatActionMongodb.java From anychat with MIT License | 5 votes |
public static long getGroupChatNum(String toTypeId, String chatCreateTime) { if (StringUtil.stringIsNull(toTypeId)) { return 0; } Date date = null; if (!StringUtil.stringIsNull(chatCreateTime)) { date = TimeUtils.stringToDateDay(chatCreateTime); } Bson filter = null; if (!StringUtil.stringIsNull(chatCreateTime)) { filter = Filters.lt(ChatObj.CHAT_CREATE_TIME, String.valueOf(date.getTime())); } long count = MongodbManager.count(toTypeId, filter); return count; }
Example #19
Source File: Mongo.java From xian with Apache License 2.0 | 5 votes |
public static <T> Page<T> findPageBySkip(MongoCollection<T> collection, Bson filter, long skip, long limit) { long total = collection.countDocuments(filter); Page<T> page = new Page<>(); page.setPageSize(new Long(limit).intValue()); page.setTotalPage(Long.valueOf(total / limit).intValue()); page.setPageNumber(Long.valueOf(skip / limit + 1).intValue()); page.setTotal(total); collection.find(filter).forEach((Consumer<T>) page.getList()::add); return page; }
Example #20
Source File: MongoPcjDocuments.java From rya with Apache License 2.0 | 5 votes |
/** * Adds binding set results to a specific PCJ. * * @param pcjId - Uniquely identifies a PCJ within Rya. (not null) * @param results - The binding set results. (not null) */ public void addResults(final String pcjId, final Collection<VisibilityBindingSet> results) { checkNotNull(pcjId); checkNotNull(results); final List<Document> pcjDocs = new ArrayList<>(); for (final VisibilityBindingSet vbs : results) { // each binding gets it's own doc. final Document bindingDoc = new Document(PCJ_ID, pcjId); vbs.forEach(binding -> { final RyaType type = RdfToRyaConversions.convertValue(binding.getValue()); bindingDoc.append(binding.getName(), new Document() .append(BINDING_TYPE, type.getDataType().stringValue()) .append(BINDING_VALUE, type.getData()) ); }); bindingDoc.append(VISIBILITIES_FIELD, vbs.getVisibility()); pcjDocs.add(bindingDoc); } pcjCollection.insertMany(pcjDocs); // update cardinality in the metadata doc. final int appendCardinality = pcjDocs.size(); final Bson query = new Document(PCJ_METADATA_ID, makeMetadataID(pcjId)); final Bson update = new Document("$inc", new Document(CARDINALITY_FIELD, appendCardinality)); pcjCollection.updateOne(query, update); }
Example #21
Source File: MongoTokenServiceImpl.java From nuls-v2 with MIT License | 5 votes |
public PageInfo<AccountTokenInfo> getContractTokens(int chainId, String contractAddress, int pageNumber, int pageSize) { Bson query = Filters.eq("contractAddress", contractAddress); Bson sort = Sorts.descending("balance"); List<Document> docsList = this.mongoDBService.pageQuery(ACCOUNT_TOKEN_TABLE + chainId, query, sort, pageNumber, pageSize); List<AccountTokenInfo> accountTokenList = new ArrayList<>(); long totalCount = mongoDBService.getCount(ACCOUNT_TOKEN_TABLE + chainId, query); for (Document document : docsList) { accountTokenList.add(DocumentTransferTool.toInfo(document, "key", AccountTokenInfo.class)); } PageInfo<AccountTokenInfo> pageInfo = new PageInfo<>(pageNumber, pageSize, totalCount, accountTokenList); return pageInfo; }
Example #22
Source File: MongoCollectionImpl.java From mongo-java-driver-reactivestreams with Apache License 2.0 | 5 votes |
@Override public Publisher<Long> countDocuments(final ClientSession clientSession, final Bson filter, final CountOptions options) { return new ObservableToPublisher<Long>(com.mongodb.async.client.Observables.observe( new Block<com.mongodb.async.SingleResultCallback<Long>>() { @Override public void apply(final com.mongodb.async.SingleResultCallback<Long> callback) { wrapped.countDocuments(clientSession.getWrapped(), filter, options, callback); } })); }
Example #23
Source File: MongoCollectionImpl.java From mongo-java-driver-rx with Apache License 2.0 | 5 votes |
@Override public Observable<UpdateResult> updateOne(final Bson filter, final Bson update, final UpdateOptions options) { return RxObservables.create(Observables.observe(new Block<SingleResultCallback<UpdateResult>>() { @Override public void apply(final SingleResultCallback<UpdateResult> callback) { wrapped.updateOne(filter, update, options, callback); } }), observableAdapter); }
Example #24
Source File: AggregationPipelineQueryNode.java From rya with Apache License 2.0 | 5 votes |
AggregationPipelineQueryNode(final MongoCollection<Document> collection, final List<Bson> pipeline, final Set<String> assuredBindingNames, final Set<String> bindingNames, final BiMap<String, String> varToOriginalName) { this.collection = Preconditions.checkNotNull(collection); this.pipeline = Preconditions.checkNotNull(pipeline); this.assuredBindingNames = Preconditions.checkNotNull(assuredBindingNames); this.bindingNames = Preconditions.checkNotNull(bindingNames); this.varToOriginalName = Preconditions.checkNotNull(varToOriginalName); }
Example #25
Source File: MongoDbDeltaCollection.java From swellrt with Apache License 2.0 | 5 votes |
/** * Create Filter to match all Wavelet deltas * * @return bson filter */ protected Bson createWaveletDBQuery() { return Filters.and( Filters.eq(MongoDbDeltaStoreUtil.FIELD_WAVE_ID, waveletName.waveId.serialise()), Filters.eq(MongoDbDeltaStoreUtil.FIELD_WAVELET_ID, waveletName.waveletId.serialise())); }
Example #26
Source File: MongoDBService.java From nuls-v2 with MIT License | 4 votes |
public String createIndex(String collName, Bson index) { MongoCollection<Document> collection = getCollection(collName); return collection.createIndex(index); }
Example #27
Source File: ReactiveMongoCollectionImpl.java From quarkus with Apache License 2.0 | 4 votes |
@Override public Uni<T> findOneAndReplace(Bson filter, T replacement) { return Wrappers.toUni(collection.findOneAndReplace(filter, replacement)); }
Example #28
Source File: GetFilterBsonVisitor.java From ditto with Eclipse Public License 2.0 | 4 votes |
@Override public Bson visitFeatureIdProperty(final String featureId, final String property) { return matchKeyValue(FIELD_FEATURES_PATH + featureId + PROPERTIES + property); }
Example #29
Source File: ReactiveMongoCollectionImpl.java From quarkus with Apache License 2.0 | 4 votes |
@Override public <D> Multi<D> aggregate(List<? extends Bson> pipeline, Class<D> clazz, AggregateOptions options) { return Multi.createFrom().publisher(apply(options, collection.aggregate(pipeline, clazz))); }
Example #30
Source File: MongoDbStore.java From swellrt with Apache License 2.0 | 4 votes |
private static Bson filterAccountBy(ParticipantId id) { return Filters.eq("_id", id.getAddress()); }