当前位置: 首页>>代码示例>>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;未经允许,请勿转载。