Java 类org.bson.conversions.Bson 实例源码

项目:mongodb-crud    文件:DeleteDocumentsImpl.java   
/**
 * 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);
    }
}
项目:athena    文件:FeatureDatabaseMgmtManager.java   
/**
 * 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;

}
项目:rebase-server    文件:FeedResource.java   
@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();
}
项目:rebase-server    文件:FeedResource.java   
@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();
}
项目:rebase-server    文件:AuthorizationResource.java   
@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();
    }
}
项目:rebase-server    文件:LicenseV1Resource.java   
/**
 * 校验激活码是否有效。如果激活码存在,并且设备 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();
}
项目:mongodb-rdbms-sync    文件:OracleToMongoEvent.java   
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;
}
项目:uavstack    文件:MongodbAggregateStrategy.java   
@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));
    }
}
项目:grain    文件:MongodbManager.java   
/**
 * 删除记录
 * 
 * @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;
    }

}
项目:OkraSync    文件:OkraSyncImpl.java   
@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));
}
项目:OkraSync    文件:IndexCreator.java   
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));
}
项目:environment.monitor    文件:ResourceLastStatusDAO.java   
/**
 * 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;
}
项目:GitHub    文件:Support.java   
/**
 * 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();
}
项目:grain    文件:MongodbManager.java   
/**
 * 查询列表
 * 
 * @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;
    }
}
项目:mongodb-crud    文件:UpdateDocumentsImpl.java   
/**
 * This method update only one one document which is matched first
 */
@Override
public void updateOneDocument() {
    MongoDatabase db = null;
    MongoCollection collection = null;
    Bson filter = null;
    Bson query = null;
    try {
        db = client.getDatabase(mongo.getDataBase());
        collection = db.getCollection(mongo.getSampleCollection());
        filter = eq("name", "Sundar");
        query = combine(set("age", 23), set("gender", "Male"));
        UpdateResult result = collection.updateOne(filter, query);
        log.info("UpdateOne Status : " + result.wasAcknowledged());
        log.info("No of Record Modified : " + result.getModifiedCount());
    } catch (MongoException e) {
        log.error("Exception occurred while update single Document : " + e, e);
    }
}
项目:digital-display-garden-iteration-2-spraguesanborn    文件:ExcelParser.java   
private static void createBeds(String[][] plants) {
    String[] keys = getKeys(plants);
    int bedCol = 1;
    for (int i = 0; i < keys.length; i++){
        if (keys[i].equals("gardenLocation")){
            bedCol = i;
            break;
        }
    }

    MongoClient mongoClient = new MongoClient();
    MongoDatabase ddg = mongoClient.getDatabase("ddg");
    MongoCollection beds = ddg.getCollection("beds");
    beds.drop();

    for (int i = 4; i < plants.length; i++){
        String currentBed = plants[i][bedCol];

        Bson filter = new Document("gardenLocation", currentBed);


        if (beds.count(filter) == 0 && !currentBed.equals("")) {
            Document doc = new Document("gardenLocation", currentBed);

            beds.insertOne(doc);
        }
    }
}
项目:dooo    文件:MongodbQuery.java   
/**
 * 与操作
 *
 * @param queries
 * @return
 */
public static MongodbQuery and(MongodbQuery... queries) {
    List<Bson> queryList = new ArrayList<Bson>();
    for (MongodbQuery query : queries) {
        if (query != null && query.getQuery() != null) {
            queryList.add(query.getQuery());
        }
    }
    return new MongodbQuery(Filters.and(queryList));
}
项目:anychat    文件:ChatActionMongodb.java   
public static ChatObj getChatById(String chatId, String chatGroupId) {
    if (StringUtil.stringIsNull(chatId) || StringUtil.stringIsNull(chatGroupId)) {
        return null;
    }
    Bson filter = Filters.eq(ChatObj.CHAT_ID, chatId);
    List<ChatObj> list = MongodbManager.find(chatGroupId, filter, ChatObj.class, 0, 0);
    if (list != null && list.size() != 0) {
        return list.get(0);
    } else {
        return null;
    }
}
项目:anychat    文件:ChatActionMongodb.java   
public static ChatObj getChatById(String chatId, String key1, String key2) {
    if (StringUtil.stringIsNull(chatId) || StringUtil.stringIsNull(key1) || StringUtil.stringIsNull(key2)) {
        return null;
    }
    Bson filter = Filters.eq(ChatObj.CHAT_ID, chatId);
    List<ChatObj> list = MongodbManager.find(getUserToUserCollectionName(key1, key2), filter, ChatObj.class, 0, 0);
    if (list != null && list.size() != 0) {
        return list.get(0);
    } else {
        return null;
    }
}
项目:anychat    文件:ChatActionMongodb.java   
public static long getUserChatNum(String toTypeId, String fromUserId, String chatCreateTime) {
    if (StringUtil.stringIsNull(toTypeId) || StringUtil.stringIsNull(fromUserId)) {
        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(getUserToUserCollectionName(toTypeId, fromUserId), filter);
    return count;
}
项目:rebase-server    文件:LicenseV2Resource.java   
@POST @Path("{_id}")
@Produces(MediaType.APPLICATION_JSON)
public Response active(@PathParam("_id") String id, @NotEmpty @QueryParam("device_id") String deviceId) {
    if (!ObjectId.isValid(id)) {
        return Responses.notFound("激活码无效");
    }
    Document license = MongoDBs.licenses().find(eq(License._ID, objectId(id))).first();
    RebaseAsserts.notNull(license, "license");
    if (!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();
}
项目:dragoman    文件:OrderByClauseParser.java   
private <T> AbstractOrderByClauseListener getListener(Class<T> clazz) {
  if (Bson.class == clazz) {
    return new MongoOrderByClauseListener();
  } else {
    throw new IllegalArgumentException(
        format(
            "Type: '%s' is not supported, the supported types are: [%s]",
            clazz.getSimpleName(), Bson.class.getSimpleName()));
  }
}
项目:dragoman    文件:SelectClauseParser.java   
private <T> AbstractSelectClauseListener getListener(Class<T> clazz) {
  if (String.class == clazz) {
    return new GroovySelectClauseListener();
  } else if (Bson.class == clazz) {
    return new MongoSelectClauseListener();
  } else {
    throw new IllegalArgumentException(
        format(
            "Type: '%s' is not supported, the supported types are: [%s, %s]",
            clazz.getSimpleName(), String.class.getSimpleName(), Bson.class.getSimpleName()));
  }
}
项目:tapir    文件:SipSessionQuery.java   
@Override
public Bson filter() {
    return Filters.and(
            between(),
            Filters.in("call_id", callIds)
    );
}
项目:dragoman    文件:MongoSelectClauseListener.java   
@Override
public Bson get() {
  List<Projection> projections = getProjections();
  BsonDocument response = new BsonDocument("_id", new BsonInt32(0));
  for (Projection p : projections) {
    response.append(p.getName(), new BsonInt32(1));
  }

  return response;
}
项目:dragoman    文件:MongoOrderByClauseListener.java   
@Override
public Bson get() {
  BsonDocument orderByObject = new BsonDocument();
  List<OrderBy> orderBys = getOrderBys();
  for (OrderBy orderBy : orderBys) {
    orderByObject.put(orderBy.getName(), new BsonInt32(orderBy.isAscending() ? 1 : -1));
  }
  return orderByObject;
}
项目:dragoman    文件:MongoRepository.java   
@Override
public Observable<Document> find(
    Dataset dataset, String select, String where, String orderBy, int maxResults) {
  MongoStorageCoordinates storageCoordinates = new MongoStorageCoordinates(dataset.getSource());
  StopWatch stopWatch = StopWatch.startForSplits();
  Bson projections = selectClauseParser.get(Bson.class, select);
  long projectionElapsedTime = stopWatch.split();

  Bson filter = whereClauseParser.get(Bson.class, where);
  long predicateElapsedTime = stopWatch.split();

  Bson order = orderByClauseParser.get(Bson.class, orderBy);
  long orderByElapsedTime = stopWatch.split();

  FindObservable<Document> findObservable =
      mongoProvider
          .provide()
          .getDatabase(storageCoordinates.getDatabaseName())
          .getCollection(storageCoordinates.getCollectionName())
          .find(filter)
          .projection(projections)
          .sort(order);

  if (maxResults > 0) {
    findObservable.limit(maxResults);
  }
  long findElapsedTime = stopWatch.split();

  long totalElapsedTime = stopWatch.stop();

  logger.info(
      "Total elapsed time for find call={}ms (projection={}ms, predicate={}ms, orderBy={}ms, find={}ms)",
      totalElapsedTime,
      projectionElapsedTime,
      predicateElapsedTime,
      orderByElapsedTime,
      findElapsedTime);

  return findObservable.toObservable();
}
项目:tapir    文件:SipSearchQuery.java   
private Bson filter(String field, String value) {
    if (isBlank(value)) {
        return null;
    }
    if (isRegex(value)) {
        return Filters.regex(field, value.replaceAll("\\*", "\\.\\*"));
    }
    return Filters.eq(field, value);
}
项目:dragoman    文件:WhereClauseParserTest.java   
@Test
public void testParseToBson() {
  Bson bson = parser.get(Bson.class, "a = 1");

  BsonDocument bsonDocument = toBsonDocument(bson);
  assertThat(bsonDocument.size(), is(1));
  assertThat(bsonDocument, hasEntry("a", new BsonInt32(1)));
}
项目:dragoman    文件:OrderByClauseParserTest.java   
@Test
public void testParseToBson() {
  Bson bson = parser.get(Bson.class, "a, b");

  BsonDocument bsonDocument = toBsonDocument(bson);
  assertThat(bsonDocument.size(), is(2));
  assertThat(bsonDocument, hasEntry("a", new BsonInt32(-1)));
  assertThat(bsonDocument, hasEntry("b", new BsonInt32(-1)));
}
项目:dragoman    文件:MongoWhereClauseListenerTest.java   
@Test
public void testInvalidPredicate() {
  SqlParserException actual =
      assertThrows(SqlParserException.class, () -> sqlParser.get(Bson.class, "a = "));
  assertThat(
      actual.getMessage(),
      containsString("Line: 1, Position: 4: no viable alternative at input '<EOF>'"));
}
项目:dragoman    文件:MongoWhereClauseListenerTest.java   
@Test
public void testCombinationOfValidAndInvalidPredicates() {
  SqlParserException actual =
      assertThrows(
          SqlParserException.class,
          () -> sqlParser.get(Bson.class, "a = 1 and b not true and c ="));
  assertThat(
      actual.getMessage(),
      containsString(
          "Line: 1, Position: 16: no viable alternative at input 'bnottrue', "
              + "Line: 1, Position: 28: no viable alternative at input '<EOF>'"));
}
项目:dragoman    文件:MongoWhereClauseListenerTest.java   
private BsonDocument parse(String where) {
  Bson bson = sqlParser.get(Bson.class, where);

  return bson.toBsonDocument(
      BsonDocument.class,
      CodecRegistries.fromProviders(new BsonValueCodecProvider(), new ValueCodecProvider()));
}
项目:dragoman    文件:MongoSelectClauseListenerTest.java   
@Test
public void testInvalidProjection() {
  SqlParserException actual =
      assertThrows(SqlParserException.class, () -> sqlParser.get(Bson.class, "a, "));
  assertThat(
      actual.getMessage(),
      containsString("Line: 1, Position: 3: no viable alternative at input '<EOF>'"));
}
项目:grain    文件:MongodbManagerTest.java   
@Test
public void testUpdateById() {
    TestMongo testMongo = new TestMongo("333", "name");
    boolean result = MongodbManager.insertOne("test_table", testMongo);
    Bson filter = Filters.and(Filters.eq("id", "333"));
    List<TestMongo> list = MongodbManager.find("test_table", filter, TestMongo.class, 0, 0);
    testMongo = list.get(0);
    testMongo.setName("name" + UUID.randomUUID().toString());
    result = MongodbManager.updateById("test_table", testMongo);
    assertEquals(true, result);
}
项目:uavstack    文件:MongodbAggregateStrategy.java   
@Override
public void concretProcessor(Object key, Map elemData, List<Bson> list) {

    BasicDBObject query = new BasicDBObject();
    QueryStrategy qry = new QueryStrategy();
    qry.concretProcessor(key, elemData, query);
    list.add(new BasicDBObject("$match", query));
}
项目:wechat-mall    文件:MongoCRUD.java   
public static int deleteById(MongoCollection<Document> col, Object id) {
    int count = 0;
    Bson filter = Filters.eq("_id", id);
    DeleteResult deleteResult = col.deleteOne(filter);
    count = (int) deleteResult.getDeletedCount();
    return count;
}
项目:wechat-mall    文件:MongoCRUD.java   
public static Document updateById(MongoCollection<Document> col, Object id, Document newDoc,
        boolean repalce) {
    Bson filter = Filters.eq("_id", id);
    if (repalce)
        col.replaceOne(filter, newDoc);
    else
        col.updateOne(filter, new Document("$set", newDoc));
    return newDoc;
}
项目:dooo    文件:MongodbQuery.java   
/**
 * 或操作
 *
 * @param queries
 * @return
 */
public static MongodbQuery or(MongodbQuery... queries) {
    List<Bson> queryList = new ArrayList<Bson>();
    for (MongodbQuery query : queries) {
        if (query != null && query.getQuery() != null) {
            queryList.add(query.getQuery());
        }
    }
    return new MongodbQuery(Filters.or(queryList));
}
项目:MooProject    文件:DatabaseConnection.java   
/**
 * Finds objects from mongoCollection
 *
 * @param collection The collection
 * @param filter     The filter (null for none)
 * @param callback   The callback
 */
public void find(MongoCollection<Document> collection, Bson filter, int limit, Consumer<FindIterable<Document>> callback) {
    this.runAsynchronous(() -> {
        if(filter != null) {
            callback.accept(collection.find(filter).limit(limit));
        }
        else {
            callback.accept(collection.find().limit(limit));
        }
    });
}