當前位置: 首頁>>代碼示例>>Java>>正文


Java Bson類代碼示例

本文整理匯總了Java中org.bson.conversions.Bson的典型用法代碼示例。如果您正苦於以下問題:Java Bson類的具體用法?Java Bson怎麽用?Java Bson使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


Bson類屬於org.bson.conversions包,在下文中一共展示了Bson類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: deleteManyDocument

import org.bson.conversions.Bson; //導入依賴的package包/類
/**
 * This is deleted delete all document(s), which is matched
 */
@Override
public void deleteManyDocument() {
	MongoDatabase db = null;
	MongoCollection collection = null;
	Bson query = null;
	try {
		db = client.getDatabase(mongo.getDataBase());
		collection = db.getCollection(mongo.getSampleCollection());
		query = lt("age", 20);
		DeleteResult result = collection.deleteMany(query);
		if (result.wasAcknowledged()) {
			log.info("Document deleted successfully \nNo of Document(s) Deleted : "
					+ result.getDeletedCount());
		}
	} catch (MongoException e) {
		log.error("Exception occurred while delete Many Document : " + e, e);
	}
}
 
開發者ID:sundarcse1216,項目名稱:mongodb-crud,代碼行數:22,代碼來源:DeleteDocumentsImpl.java

示例2: getFilterBson

import org.bson.conversions.Bson; //導入依賴的package包/類
public static Bson getFilterBson(MatchOperator operator , String attributeName , Object value){
	Bson filter = null;
	switch(operator){
	case GT : 
		filter=Filters.gt(attributeName, value);
		break;
	case LT : 
		filter=Filters.lt(attributeName, value);
		break;
	case GTE : 
		filter=Filters.gte(attributeName, value);
		break;
	case LTE : 
		filter=Filters.lte(attributeName, value);
		break;
	case EQ :
		filter=Filters.eq(attributeName, value);
		break;
	case NE : 
		filter=Filters.ne(attributeName, value);
		break;
	default :
		filter=Filters.eq(attributeName, value);
		break;
	}
	return filter;
}
 
開發者ID:gagoyal01,項目名稱:mongodb-rdbms-sync,代碼行數:28,代碼來源:MongoDbUtilities.java

示例3: deleteById

import org.bson.conversions.Bson; //導入依賴的package包/類
/**
 * 刪除記錄
 * 
 * @param collectionName
 *            表名
 * @param mongoObj
 *            記錄
 * @return
 */
public static boolean deleteById(String collectionName, MongoObj mongoObj) {
	MongoCollection<Document> collection = getCollection(collectionName);
	try {
		Bson filter = Filters.eq(MongoConfig.MONGO_ID, mongoObj.getDocument().getObjectId(MongoConfig.MONGO_ID));
		DeleteResult result = collection.deleteOne(filter);
		if (result.getDeletedCount() == 1) {
			return true;
		} else {
			return false;
		}
	} catch (Exception e) {
		if (log != null) {
			log.error("刪除記錄失敗", e);
		}
		return false;
	}

}
 
開發者ID:dianbaer,項目名稱:grain,代碼行數:28,代碼來源:MongodbManager.java

示例4: generateBson

import org.bson.conversions.Bson; //導入依賴的package包/類
/**
 * Converting User-defined constaints to Bson constraints.
 *
 * @param featureConstraint
 * @return
 */
public Bson generateBson(FeatureConstraint featureConstraint) {
    List<TargetAthenaValue> dataRequestObjectValueList = featureConstraint.getDataRequestObjectValueList();
    FeatureConstraintOperatorType featureConstraintOperatorType =
            featureConstraint.getFeatureConstraintOperatorType();
    Bson query = null;

    if (!(dataRequestObjectValueList.size() > 0)) {
        return null;
    }

    if (featureConstraintOperatorType == FeatureConstraintOperatorType.COMPARABLE) {
        query = getBsonFromRequestOperatorComparison(featureConstraint);

    } else if (featureConstraintOperatorType == FeatureConstraintOperatorType.LOGICAL) {
        query = getBsonFromRequestOperatorLogical(featureConstraint);

    } else {
        log.warn("not supported FeatureConstraintOperatorType");
    }

    return query;

}
 
開發者ID:shlee89,項目名稱:athena,代碼行數:30,代碼來源:FeatureDatabaseMgmtManager.java

示例5: readAll

import org.bson.conversions.Bson; //導入依賴的package包/類
@GET @Produces(MediaType.APPLICATION_JSON)
public Response readAll(
    @NotEmptyButNull @QueryParam("last_id") String lastId,
    @Range(min = 1, max = Globals.MAX_SIZE) @DefaultValue("20") @QueryParam("size") int size) {

    RebaseAsserts.existCategory(category);
    List<Document> feeds = new ArrayList<>();
    List<Bson> filters = new ArrayList<>();
    if (lastId != null) {
        filters.add(lt(Feed._ID, objectId(lastId)));
    }
    filters.add(eq(Feed.CATEGORY, category));
    filters.add(eq(Feed.OWNER, owner));
    MongoDBs.feeds().find().sort(descending(Feed._ID))
        .filter(and(filters))
        .limit(size)
        .into(feeds);
    return Response.ok(feeds).build();
}
 
開發者ID:drakeet,項目名稱:rebase-server,代碼行數:20,代碼來源:FeedResource.java

示例6: editFeed

import org.bson.conversions.Bson; //導入依賴的package包/類
@PATCH @Path("{_id}")
public Response editFeed(@PathParam("_id") String _id, @NotNull Feed input) {
    Authorizations.verify(owner, auth);
    if (!isNullOrEmpty(input.category)) {
        RebaseAsserts.existCategory(input.category);
    }
    final Bson target = eq(Feed._ID, objectId(_id));
    MongoDBs.feeds().updateOne(target,
        combine(filterNotNull(
            optionalSet(Feed.TITLE, input.title),
            optionalSet(Feed.CONTENT, input.content),
            optionalSet(Feed.URL, input.url),
            optionalSet(Feed.CATEGORY, input.category),
            optionalSet(Feed.COVER_URL, input.coverUrl),
            currentDate(Feed.UPDATED_AT))
        )
    );
    Document feed = MongoDBs.feeds().find(target).first();
    RebaseAsserts.notNull(feed, "feed");
    return Response.ok(feed).build();
}
 
開發者ID:drakeet,項目名稱:rebase-server,代碼行數:22,代碼來源:FeedResource.java

示例7: authorize

import org.bson.conversions.Bson; //導入依賴的package包/類
@GET @Path("{username}")
@Produces(MediaType.APPLICATION_JSON)
public Response authorize(
    @Username @PathParam("username") String username,
    @NotEmpty @QueryParam("password") String password) {

    Bson filter = and(eq(User.USERNAME, username), eq(User.PASSWORD, Hashes.sha1(password)));
    Document newAuth = Authorizations.newInstance(username);
    Document user = MongoDBs.users().findOneAndUpdate(filter, set(User.AUTHORIZATION, newAuth));
    if (user == null) {
        return Response.status(FORBIDDEN)
            .entity(new Failure("The username or password is incorrect"))
            .build();
    } else {
        return Response.ok(newAuth).build();
    }
}
 
開發者ID:drakeet,項目名稱:rebase-server,代碼行數:18,代碼來源:AuthorizationResource.java

示例8: verify

import org.bson.conversions.Bson; //導入依賴的package包/類
/**
 * 校驗激活碼是否有效。如果激活碼存在,並且設備 ID 沒變,則返回原 License 對象。如果不存在,返回錯誤信息。
 * 如果存在,但設備變了,則根據 override 覆蓋使用新的設備 ID。
 *
 * @param id 激活碼 key
 * @param deviceId 設備 ID
 * @param override 是否覆蓋設備 ID
 * @return 如果激活碼有效,返回最新 License,否則返回錯誤
 */
@GET @Path("{_id}")
@Produces(MediaType.APPLICATION_JSON)
public Response verify(
    @PathParam("_id") String id,
    @QueryParam("device_id") String deviceId,
    @QueryParam("override") boolean override) {

    if (override && isEmpty(deviceId)) {
        return Responses.badRequest("device_id required");
    }
    Document license = MongoDBs.licenses().find(eq(License._ID, objectId(id))).first();
    RebaseAsserts.notNull(license, "license");
    if (override && !Objects.equals(deviceId, license.getString(License.DEVICE_ID))) {
        final Bson target = eq(License._ID, objectId(id));
        MongoDBs.licenses().updateOne(target, set(License.DEVICE_ID, deviceId));
        license.put(License.DEVICE_ID, deviceId);
    }
    return Response.ok(license).build();
}
 
開發者ID:drakeet,項目名稱:rebase-server,代碼行數:29,代碼來源:LicenseV1Resource.java

示例9: getRangeBson

import org.bson.conversions.Bson; //導入依賴的package包/類
private Bson getRangeBson(MatchOperation matchOperation , String attributeName){
	Object literalValue=null;
	Bson filter =null;
	if(matchOperation!=null){
		MatchAble rightExpression =matchOperation.getRightExpression();
		if(rightExpression instanceof Literal){
			literalValue = ((Literal)rightExpression).getLiteralValue();
		}else{
			Literal leftExpression =(Literal) matchOperation.getLeftExpression();
			literalValue = leftExpression.getLiteralValue();
		}
		MatchOperator matchOperator = matchOperation.getOperator();
		filter = MongoDbUtilities.getFilterBson(matchOperator, attributeName, literalValue);			
	}
	return filter;
}
 
開發者ID:gagoyal01,項目名稱:mongodb-rdbms-sync,代碼行數:17,代碼來源:OracleToMongoEvent.java

示例10: concretProcessor

import org.bson.conversions.Bson; //導入依賴的package包/類
@Override
public void concretProcessor(Object key, Map elemData, List<Bson> list) {

    if (null == key && null == elemData) {
        list.add(new BasicDBObject("$project",
                new BasicDBObject("_id", 0).append(DataStoreProtocol.RESULT, "$" + DataStoreProtocol.RESULT)));
    }
    else {
        Document filterBson = new Document();
        filterBson.append("_id", 0);
        String fileds = (String) elemData.get(DataStoreProtocol.FIELDS);
        if (!StringHelper.isEmpty(fileds)) {
            String[] filters = fileds.split(";");
            for (String filter : filters) {
                filterBson.append(filter, 1);
            }
        }

        list.add(new BasicDBObject("$project", filterBson));
    }
}
 
開發者ID:uavorg,項目名稱:uavstack,代碼行數:22,代碼來源:MongodbAggregateStrategy.java

示例11: peek

import org.bson.conversions.Bson; //導入依賴的package包/類
@Override
public Optional<T> peek() {
    final Bson peekQuery = QueryUtil.generatePeekQuery(defaultHeartbeatExpirationMillis);

    final Document update = new Document();
    update.put("heartbeat", new Date());
    update.put("status", OkraStatus.PROCESSING.name());

    final FindOneAndUpdateOptions options = new FindOneAndUpdateOptions();
    options.returnDocument(ReturnDocument.AFTER);

    final Document document = client
            .getDatabase(getDatabase())
            .getCollection(getCollection())
            .findOneAndUpdate(peekQuery, new Document("$set", update), options);

    if (document == null) {
        return Optional.empty();
    }

    return Optional.ofNullable(serializer.fromDocument(scheduleItemClass, document));
}
 
開發者ID:OkraScheduler,項目名稱:OkraSync,代碼行數:23,代碼來源:OkraSyncImpl.java

示例12: ensureIndexes

import org.bson.conversions.Bson; //導入依賴的package包/類
public static <T extends OkraItem> void ensureIndexes(final Okra<T> okra,
                                                      final MongoClient mongo,
                                                      final String database,
                                                      final String collection) {
    okra.getIndexDefs()
            .stream()
            .map(indexDef -> {
                final boolean ascending = indexDef.getOrdering() == null
                        || indexDef.getOrdering().equals(Ordering.ASC);

                final Bson ordering = ascending
                        ? Indexes.ascending(indexDef.getAttrs()) : Indexes.descending(indexDef.getAttrs());

                return mongo
                        .getDatabase(database)
                        .getCollection(collection)
                        .createIndex(ordering);
            })
            .forEach(indexName -> LOGGER.info("Done. Index name: {}", indexName));
}
 
開發者ID:OkraScheduler,項目名稱:OkraSync,代碼行數:21,代碼來源:IndexCreator.java

示例13: find

import org.bson.conversions.Bson; //導入依賴的package包/類
/**
 * Get last statuses for particular environment and defined resources
 * @param environmentName environment to fetch statuses for
 * @param resourceIds resources to fetch statuses for
 * @return
 */
public List<ResourceStatus> find(String environmentName, Set<String> resourceIds) {
  Bson query = and(
      eq("environmentName", environmentName),
      in("resource.resourceId", resourceIds)
  );

  List<ResourceStatus> resources = thisCollection.find(query)
      .map(DocumentMapper::resourceStatusFromDocument)
      .into(new ArrayList<>());

  return resources;
}
 
開發者ID:YagelNasManit,項目名稱:environment.monitor,代碼行數:19,代碼來源:ResourceLastStatusDAO.java

示例14: convertToBson

import org.bson.conversions.Bson; //導入依賴的package包/類
/**
 * Given a query / ordering clause will convert it to Bson representation.
 */
public static Bson convertToBson(final Constraints.ConstraintHost fields) {
  if (fields instanceof JsonQuery) {
    return Document.parse(((JsonQuery) fields).value);
  }
  return fields.accept(new ConstraintBuilder("")).asDocument();
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:10,代碼來源:Support.java

示例15: find

import org.bson.conversions.Bson; //導入依賴的package包/類
/**
 * 查詢列表
 * 
 * @param collectionName
 *            表名
 * @param filter
 *            過濾條件
 * @param clazz
 *            類名
 * @param start
 *            開始條數
 * @param pageSize
 *            多少條
 * @return
 */
public static <T> List<T> find(String collectionName, Bson filter, Class<T> clazz, int start, int pageSize) {
	MongoCollection<Document> collection = getCollection(collectionName);
	try {
		MongoCursor<Document> iterator = null;
		if (pageSize == 0) {
			if (filter == null) {
				iterator = collection.find().iterator();
			} else {
				iterator = collection.find(filter).iterator();
			}
		} else {
			if (filter == null) {
				iterator = collection.find().skip(start).limit(pageSize).iterator();
			} else {
				iterator = collection.find(filter).skip(start).limit(pageSize).iterator();
			}
		}
		ArrayList<T> list = new ArrayList<>();
		while (iterator.hasNext()) {
			Document document = iterator.next();
			T obj = documentToObject(document, clazz);
			MongoObj mongoObj = (MongoObj) obj;
			mongoObj.setDocument(document);
			list.add(obj);
		}
		return list;
	} catch (Exception e) {
		if (log != null) {
			log.error("查詢documentList失敗", e);
		}
		return null;
	}
}
 
開發者ID:dianbaer,項目名稱:grain,代碼行數:49,代碼來源:MongodbManager.java


注:本文中的org.bson.conversions.Bson類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。