Java 类com.mongodb.client.MongoCollection 实例源码

项目: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);
    }
}
项目:digital-display-garden-iteration-3-sixguysburgers-fries    文件:UnorganizedTests.java   
@Test
public void incrementMetadata() {
//This method is called from inside of getPlantByPlantId();
    boolean myPlant = plantController.
            incrementMetadata("58d1c36efb0cac4e15afd278", "pageViews");
    assertFalse(myPlant);
    boolean myPlant2 = plantController.incrementMetadata("16001.0","pageViews");
    assertTrue(myPlant2);


//This is necessary to test the data separately from getPlantByPlantId();
    Document searchDocument = new Document();
    searchDocument.append("id", "16001.0");
    MongoClient mongoClient = new MongoClient();
    MongoDatabase db = mongoClient.getDatabase(databaseName);
    MongoCollection<Document> plantCollection = db.getCollection("plants");
    String before = JSON.serialize(plantCollection.find(searchDocument));
    plantController.incrementMetadata("16001.0","pageViews");
    String after = JSON.serialize(plantCollection.find(searchDocument));

    assertFalse(before.equals(after));
}
项目:Smart_City    文件:ReportDAO.java   
/**
 * Inserts a new report to the DB
 * 
 * @param report contains all data for insertion
 */
public static void insertReport(Report report) {
    Document newDocument = new Document();
    newDocument.append("priority", report.getPriority())
            .append("comment", report.getComment())
            .append("resolved", report.isResolved())
            .append("city_item_id", report.getCityItemId());

    if (report.getReportDate() != null) {
        newDocument.append("report_date", report.getReportDate().getTime());
    }
    if (report.getResolveDate() != null) {
        newDocument.append("resolve_date", report.getResolveDate().getTime());
    }

    MongoDatabase db = Configurator.INSTANCE.getDatabase();
    MongoCollection collection = db.getCollection(COLLECTION);
    collection.insertOne(newDocument); //TODO check if succeeds
}
项目:GitHub    文件:Repositories.java   
protected Repository(
    RepositorySetup configuration,
    String collectionName,
    Class<T> type) {

  this.configuration = checkNotNull(configuration, "configuration");
  checkNotNull(collectionName, "collectionName");
  checkNotNull(type, "type");

  final TypeAdapter<T> adapter = checkAdapter(configuration.gson.getAdapter(type), type);
  final MongoCollection<Document> collection = configuration.database.getCollection(collectionName);
  // combine default and immutables codec registries
  final CodecRegistry registry = CodecRegistries.fromRegistries(collection.getCodecRegistry(), BsonEncoding.registryFor(type, adapter));

  this.collection = collection
      .withCodecRegistry(registry)
      .withDocumentClass(type);
}
项目:mongodb-crud    文件:UpdateDocumentsImpl.java   
/**
 * This method update document with lastmodified properties 
 */
@Override
public void updateDocumentWithCurrentDate() {
    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"),
                currentDate("lastModified"));
        UpdateResult result = collection.updateOne(filter, query);
        log.info("Update with date Status : " + result.wasAcknowledged());
        log.info("No of Record Modified : " + result.getModifiedCount());
    } catch (MongoException e) {
        log.error("Exception occurred while update Many Document with Date : " + e, e);
    }
}
项目:digital-display-garden-iteration-4-dorfner-v2    文件:FlowerRating.java   
@Test
public void AddFlowerRatingReturnsTrueWithValidJsonInput() throws IOException{

    String json = "{like: true, id: \"58d1c36efb0cac4e15afd202\"}";

    assertTrue(plantController.addFlowerRating(json, "first uploadId") instanceof ObjectId);

    MongoClient mongoClient = new MongoClient();
    MongoDatabase db = mongoClient.getDatabase(databaseName);
    MongoCollection plants = db.getCollection("plants");

    FindIterable doc = plants.find(new Document().append("_id", new ObjectId("58d1c36efb0cac4e15afd202")));
    Iterator iterator = doc.iterator();
    Document result = (Document) iterator.next();

    List<Document> ratings = (List<Document>) ((Document) result.get("metadata")).get("ratings");
    assertEquals(1, ratings.size());

    Document rating = ratings.get(0);
    assertTrue(rating.getBoolean("like"));
    assertTrue(rating.get("id") instanceof ObjectId);
}
项目:digital-display-garden-iteration-4-dorfner-v2    文件:TestPlantComment.java   
@Test
public void successfulInputOfComment() throws IOException {
    String json = "{ plantId: \"58d1c36efb0cac4e15afd278\", comment : \"Here is our comment for this test\" }";

    assertTrue(plantController.addComment(json, "second uploadId"));

    MongoClient mongoClient = new MongoClient();
    MongoDatabase db = mongoClient.getDatabase(databaseName);
    MongoCollection<Document> plants = db.getCollection("plants");

    Document filterDoc = new Document();

    filterDoc.append("_id", new ObjectId("58d1c36efb0cac4e15afd278"));
    filterDoc.append("uploadID", "second uploadId");

    Iterator<Document> iter = plants.find(filterDoc).iterator();

    Document plant = iter.next();
    List<Document> plantComments = (List<Document>) ((Document) plant.get("metadata")).get("comments");
    long comments = plantComments.size();

    assertEquals(1, comments);
    assertEquals("Here is our comment for this test", plantComments.get(0).getString("comment"));
    assertNotNull(plantComments.get(0).getObjectId("_id"));
  }
项目:Jerkoff    文件:MongoTest.java   
@Test
@Ignore
public void testInsert() {
    MongoClient mongoClient = new MongoClient("localhost", 27017);
    try {
        MongoDatabase db = mongoClient.getDatabase("prova");
        MongoCollection<Document> coll = db.getCollection("prova");
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("signature", "void test()");
        map.put("param", convert(new Object[0]));
        map.put("returnValue", 1);
        map.put("exception", convert(new IllegalAccessError("prova")));
        Document doc = new Document(map);
        coll.insertOne(doc);
        LOG.info(doc);
    } catch (Exception e) {
        LOG.error(e);
    } finally {
        mongoClient.close();
    }
}
项目:Smart_City    文件:CityItemDAO.java   
/**
 *
 * @param cityItem Wrapper object for JSON values
 * @return id of inserted document
 */
public static String insertCityItem(CityItem cityItem)
{
    ObjectId id = new ObjectId();
    Document post = new Document();
    post.put("_id",id);
    post.put("type", Integer.toString(cityItem.getType()));
    post.put("location",new Document("x",String.valueOf(cityItem.getLongitude()))
            .append("y",String.valueOf(cityItem.getLatitude())));
    post.put("description", cityItem.getDescription());
    MongoCollection<Document> collection = Configurator.INSTANCE.getDatabase().getCollection(COLLECTION);
    try {
        collection.insertOne(post);
        return id.toString();
    } catch (DuplicateKeyException e) {
        e.printStackTrace();
        return "-1";
    }
}
项目:nectar-server    文件:FTSController.java   
private static void buildChecksumDir(File dir, boolean isPublic, MongoCollection<Document> index) throws IOException {
    File[] contents = dir.listFiles();
    if(contents == null) return;

    List<Document> toInsert = new CopyOnWriteArrayList<>();

    for(File file : contents) {
        if(file.isDirectory()) {
            // Recursion: build for all in that directory
            buildChecksumDir(file, isPublic, index);
        } else {
            NectarServerApplication.getThreadPoolTaskExecutor().submit(() -> {
                try {
                    buildChecksumFile(file, index, toInsert, isPublic);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            });
        }
    }

    if(!toInsert.isEmpty()) {
        index.insertMany(toInsert);
    }
}
项目:uavstack    文件:MongoDBDataStore.java   
@SuppressWarnings({ "rawtypes", "unchecked" })
private List<Map> countAction(DataStoreMsg msg, Map queryparmes, MongoCollection<Document> collection) {

    BasicDBObject query = new BasicDBObject();// output

    Map findparmes = (Map) queryparmes.get(DataStoreProtocol.WHERE);
    QueryStrategy qry = new QueryStrategy();
    Map express = new LinkedHashMap();
    express.put(DataStoreProtocol.FIND, findparmes);
    qry.concretProcessor(DataStoreProtocol.FIND, express, query);

    // for (Object qobj : query.keySet()) {
    // log.info(this, "shell in package:" + qobj.toString() + ":" + query.get(qobj));
    // }

    log.info(this, "MongoDBDataStore countAction toJson : " + query.toJson());

    long countN = collection.count(query);
    Map<String, Object> item = new LinkedHashMap<String, Object>();
    item.put(DataStoreProtocol.COUNT, countN);
    List<Map> res = new ArrayList<Map>();
    res.add(item);

    return res;

}
项目:digital-display-garden-iteration-4-revolverenguardia-1    文件:FlowerRating.java   
@Test
public void AddFlowerRatingReturnsTrueWithValidJsonInput() throws IOException{

    String json = "{like: true, id: \"16001.0\"}";

    assertTrue(plantController.addFlowerRating(json, "first uploadId"));

    MongoCollection plants = testDB.getCollection("plants");

    FindIterable doc = plants.find(new Document().append("_id", new ObjectId("58d1c36efb0cac4e15afd202")));
    Iterator iterator = doc.iterator();
    Document result = (Document) iterator.next();

    List<Document> ratings = (List<Document>) ((Document) result.get("metadata")).get("ratings");
    assertEquals(1, ratings.size());

    Document rating = ratings.get(0);
    assertTrue(rating.getBoolean("like"));
    assertEquals(new ObjectId("58d1c36efb0cac4e15afd202"),rating.get("ratingOnObjectOfId"));
}
项目:athena    文件:ReplicateDatabaseData.java   
public HashMap<String, MongoCollection> getCollectionList(MongoDatabase mongoDatabase) {
    HashMap<String, MongoCollection> dbCollectionList = new HashMap<String, MongoCollection>();
    String[] tableNameList = {athenaFeatureField.ERROR_MSG, athenaFeatureField.FLOW_REMOVED, athenaFeatureField.PACKET_IN,
            athenaFeatureField.PORT_STATUS, athenaFeatureField.FLOW_STATS, athenaFeatureField.QUEUE_STATS,
            athenaFeatureField.AGGREGATE_STATS, athenaFeatureField.TABLE_STATS, athenaFeatureField.PORT_STATS, "terabyte"};
    String teraBytes = "terabyte";

    for (String tableName : tableNameList) {
        MongoCollection dbCollection = mongoDatabase.getCollection(tableName);
        if (dbCollection == null) {
            mongoDatabase.createCollection(tableName);
            dbCollection = mongoDatabase.getCollection(tableName);
        }
        dbCollectionList.put(tableName, dbCollection);
    }

    return dbCollectionList;
}
项目:dooo    文件:MongodbDataAccess.java   
/**
 * 查询
 *
 * @param clazz          类
 * @param collectionName 集合名
 * @param sort           排序
 * @param <T>
 * @return
 */
public <T> List<T> findAll(Class<T> clazz, String collectionName, MongodbSort sort) {
    List<T> resultMapList = new ArrayList<T>();
    MongoCollection<Document> collection = sMongoDatabase.getCollection(collectionName);
    FindIterable<Document> findIterable = collection.find();
    if(sort != null) {
        findIterable.sort(sort.getDbObject());
    }
    MongoCursor<Document> cursor = findIterable.iterator();
    try {
        while (cursor.hasNext()) {
            Document document = cursor.next();
            T parseObject = JSON.parseObject(JSON.toJSONString(document), clazz);
            resultMapList.add(parseObject);
        }
    } finally {
        cursor.close();
    }

    return resultMapList;
}
项目:digital-display-garden-iteration-4-revolverenguardia-1    文件:TestBedController.java   
@Test
public void TestBedVisit(){
    bedController.addBedVisit("10.0","first uploadId");
    MongoCollection beds = testDB.getCollection("beds");

    FindIterable doc = beds.find(new Document().append("_id", new ObjectId("58d1c36efb0cac4e15afd303")));
    Iterator iterator = doc.iterator();
    Document result = (Document) iterator.next();
    //System.out.println(result);

    List<Document> bedVisits =  (List<Document>)((Document) result.get("metadata")).get("bedVisits");
    //System.out.println(bedVisits);
    assertEquals("",1 ,bedVisits.size());

    Document visits = bedVisits.get(0);
    //System.out.println(visits.get("visit"));
    ObjectId objectId = new ObjectId();

    String v = visits.get("visit").toString();

    //checking to see that the type of visit is an of type/structure of ObjectID
    assertEquals("they should both be of type org.bson.types.ObjectId ",objectId.getClass().getName(),visits.get("visit").getClass().getName());
    assertEquals("the object id produced from a visit must be 24 characters",24,v.length());

}
项目:Jerkoff    文件:MongoDBDaoImpl.java   
@Override
public List<Document> find(String collection, String signature) {
    List<Document> res = new ArrayList<Document>();
    try {
        MongoDatabase db = mongoClient.getDatabase(databaseName);
        MongoCollection<Document> coll = db.getCollection(collection);
        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.put("signature", signature);
        Iterable<Document> docs = coll.find(searchQuery);
        for (Document doc : docs) {
            res.add(doc);
        }
    } catch (Exception e) {
        LOG.error(e);
    }
    return res;
}
项目:digital-display-garden-iteration-3-sixguysburgers-fries    文件:FlowerRating.java   
@Test
public void AddFlowerRatingReturnsTrueWithValidJsonInput() throws IOException{

    String json = "{like: true, id: \"58d1c36efb0cac4e15afd202\"}";

    assertTrue(plantController.addFlowerRating(json, "first uploadId"));

    MongoClient mongoClient = new MongoClient();
    MongoDatabase db = mongoClient.getDatabase(databaseName);
    MongoCollection plants = db.getCollection("plants");

    FindIterable doc = plants.find(new Document().append("_id", new ObjectId("58d1c36efb0cac4e15afd202")));
    Iterator iterator = doc.iterator();
    Document result = (Document) iterator.next();

    List<Document> ratings = (List<Document>) ((Document) result.get("metadata")).get("ratings");
    assertEquals(1, ratings.size());

    Document rating = ratings.get(0);
    assertTrue(rating.getBoolean("like"));
    assertEquals(new ObjectId("58d1c36efb0cac4e15afd202"),rating.get("ratingOnObjectOfId"));
}
项目:dooo    文件:MongodbDataAccess.java   
/**
 * 查询一个
 *
 * @param collectionName 集合名
 * @param query          查询条件
 * @param fields         返回字段或者排除字段
 * @param sort
 * @return
 */
public Map<String, Object> findOne(
        String collectionName,
        MongodbQuery query, MongodbFields fields, MongodbSort sort) {
    MongoCollection<Document> collection = sMongoDatabase.getCollection(collectionName);
    FindIterable<Document> findIterable = collection.find(query.getQuery());
    if (fields == null) {
        findIterable.projection(new MongodbFields().getDbObject());
    } else {
        findIterable.projection(fields.getDbObject());
    }
    if (sort != null) {
        findIterable.sort(sort.getDbObject());
    }
    findIterable.limit(1);
    MongoCursor<Document> cursor = findIterable.iterator();
    try {
        if (cursor.hasNext()) {
            return cursor.next();
        }
    } finally {
        cursor.close();
    }
    return null;
}
项目:mongodb-rdbms-sync    文件:MngToOrclReader.java   
@Override
public void run() {
    System.out.println("Reader started");
    MongoCollection<Document> collection = DBCacheManager.INSTANCE.getCachedMongoPool(mongoDbName, mongoUserName)
            .getDatabase(mongoDbName).getCollection(collectionName);
    FindIterable<Document> it = collection.find().batchSize(batchSize);
    it.forEach(new Block<Document>() {
        @Override
        public void apply(Document t) {
            System.out.println("Document read " + t);
            try {
                dataBuffer.put(t);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });
}
项目:config    文件:MongoConfigRepository.java   
@Override
public List<KeyValueConfigEntity> findAll(@Nonnull KeyValueConfigName configName) throws Exception {
  Objects.requireNonNull(configName);

  String collectionName = configName.getQualifiedName();
  MongoCollection<RawBsonDocument> collection =
      connector.getDatabase().getCollection(collectionName, RawBsonDocument.class);

  MongoCursor<RawBsonDocument> it = collection.find().iterator();
  if (!it.hasNext()) {
    return Collections.emptyList();
  }

  RawBsonDocument document = it.next();
  ByteArrayInputStream bin = new ByteArrayInputStream(document.getByteBuffer().array());
  ObjectMapper objectMapper = MongoConfigObjectMapper.getInstance();
  ObjectReader objectReader = objectMapper.readerFor(MongoConfigEntity.class);
  List<KeyValueConfigEntity> result = ((MongoConfigEntity) objectReader.readValue(bin)).getConfig();

  // set groupName on returned config key-value pairs
  return result.stream().map(input -> input.setConfigName(configName)).collect(Collectors.toList());
}
项目:grain    文件:MongodbManager.java   
/**
 * 插入list
 * 
 * @param collectionName
 *            表名
 * @param list
 *            list
 * @return
 */
public static boolean insertMany(String collectionName, List<MongoObj> list) {
    MongoCollection<Document> collection = getCollection(collectionName);
    try {
        ArrayList<Document> documentList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            MongoObj mongoObj = list.get(i);
            Document document = objectToDocument(mongoObj);
            documentList.add(document);
        }
        collection.insertMany(documentList);
        return true;
    } catch (Exception e) {
        if (log != null) {
            log.error("插入documentList失败", e);
        }
        return false;
    }
}
项目: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;
    }

}
项目:polymorphia    文件:UpdateTest.java   
@Test
public void updatePojoTest() {

    Bson update = combine(set("user", "Jim"),
            set("action", Action.DELETE),
            // unfortunately at this point we need to provide a non generic class, so the codec is able to determine all types
            // remember: type erasure makes it impossible to retrieve type argument values at runtime
            // @todo provide a mechanism to generate non-generic class on the fly. Is that even possible ?
            // set("listOfPolymorphicTypes", buildNonGenericClassOnTheFly(Arrays.asList(new A(123), new B(456f)), List.class, Type.class),
            set("listOfPolymorphicTypes", new PolymorphicTypeList(Arrays.asList(new A(123), new B(456f)))),
            currentDate("creationDate"),
            currentTimestamp("_id"));

    FindOneAndUpdateOptions findOptions = new FindOneAndUpdateOptions();
    findOptions.upsert(true);
    findOptions.returnDocument(ReturnDocument.AFTER);

    MongoCollection<Pojo> pojoMongoCollection = mongoClient.getDatabase("test").getCollection("documents").withDocumentClass(Pojo.class);

    Pojo pojo = pojoMongoCollection.findOneAndUpdate(Filters.and(Filters.lt(DBCollection.ID_FIELD_NAME, 0),
            Filters.gt(DBCollection.ID_FIELD_NAME, 0)), update, findOptions);

    assertNotNull(pojo.id);
}
项目:nifi-nars    文件:UpdateMongoIT.java   
@Test
public void testPushUpdate() throws Exception {
    final TestRunner runner = TestRunners.newTestRunner(new UpdateMongo());
    addMongoService(runner);
    runner.setProperty(MongoProps.DATABASE, MONGO_DATABASE_NAME);
    runner.setProperty(MongoProps.COLLECTION, "insert_test");
    runner.setProperty(MongoProps.UPDATE_QUERY_KEYS, "d.id");
    runner.setProperty(MongoProps.UPDATE_KEYS, "d.media");
    runner.setProperty(MongoProps.UPDATE_OPERATOR, "$addToSet");

    String contents = FileUtils.readFileToString(Paths.get("src/test/resources/update_payload.json").toFile());

    runner.enqueue(contents.getBytes());
    runner.run();

    runner.assertTransferCount(AbstractMongoProcessor.REL_FAILURE, 0);
    runner.assertTransferCount(AbstractMongoProcessor.REL_SUCCESS, 1);

    // Verify whether the update was made
    MongoClient client = mongo.getMongoClient();
    MongoDatabase db = client.getDatabase(MONGO_DATABASE_NAME);
    if (db != null) {
        MongoCollection<Document> collection = db.getCollection("insert_test");
        Document query = buildQuery("d.id", (JsonObject) JSON_PROVIDER.parse(contents));
        assertEquals(1, collection.count(query.append("d.media", new Document("$exists", true))));
    }
}
项目:sagiri    文件:Sagiri.java   
public static MongoCollection getCollection(String suffix) {
    String className = Thread.currentThread().getStackTrace()[2].getClassName();

    for(PluginBubble bubble : getPlugins()) {
        String packageName = bubble.getPlugin().getClass().getPackage().getName();

        if(className.startsWith(packageName)) {
            return mongoDatabase.getCollection(
                    String.format("%s_%s", packageName, suffix)
            );
        }
    }

    return null;
}
项目:grain    文件:MongodbManager.java   
/**
 * 获取个数
 * 
 * @param collectionName
 *            表名
 * @param filter
 *            过滤
 * @return
 */
public static long count(String collectionName, Bson filter) {
    MongoCollection<Document> collection = getCollection(collectionName);
    try {
        if (filter == null) {
            return collection.count();
        } else {
            return collection.count(filter);
        }
    } catch (Exception e) {
        if (log != null) {
            log.error("查询个数失败", e);
        }
        return 0;
    }

}
项目:mongodb-crud    文件:QueryDocumentsImpl.java   
/**
 * This method retrieve document(s) based on parameters
 * @param query - query have to execute
 * @param operator - this is for debug purpose
 */
private void getData(Bson query, String operator) {
    MongoDatabase db = null;
    MongoCollection collection = null;
    try {
        db = client.getDatabase(mongo.getDataBase());
        collection = db.getCollection(mongo.getSampleCollection());
        FindIterable<Document> list = collection.find(query);
        for (Document doc : list) {
            log.info(doc.getString("name"));
        }
    } catch (MongoException e) {
        log.error("exception occurred while getting Document using " + operator + " : " + e, e);
    }
}
项目: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);
    }
}
项目:rocketmq-flink-plugin    文件:MongoManager.java   
/**
 * @param dbName         库名
 * @param collectionName 集合名
 * @param json1          条件
 * @param json2          保存doc
 * @return upsert结果信息
 */
public JSONObject executeUpsert(String dbName, String collectionName, JSONObject json1, JSONObject json2) {
    JSONObject resp = new JSONObject();
    try {
        MongoDatabase db = mongoClient.getDatabase(dbName);
        MongoCollection coll = db.getCollection(collectionName);
        JSONObject saveJson = new JSONObject();
        saveJson.put("$set", json2);
        Document doc1 = Document.parse(json1.toString());
        Document doc2 = Document.parse(saveJson.toString());
        UpdateOptions up = new UpdateOptions();
        up.upsert(true);
        UpdateResult ur = coll.updateOne(doc1, doc2, up);
        if (ur.isModifiedCountAvailable()) {
            if (json1.containsKey(ID)) {
                resp.put("Data", json1.get(ID));
            } else {
                resp.put("Data", json1);
            }
        }
    } catch (MongoTimeoutException e1) {
        e1.printStackTrace();
        resp.put("ReasonMessage", e1.getClass() + ":" + e1.getMessage());
        return resp;
    } catch (Exception e) {
        e.printStackTrace();
        resp.put("ReasonMessage", e.getClass() + ":" + e.getMessage());
    }
    return resp;
}
项目:intellead-integration-tests    文件:Steps.java   
@Then("^Lead with id (\\d+) should be in the database")
public void Lead_with_id_should_be_in_intellead_data_mongodb_database(int leadId) {
    MongoDatabase database = mongoClientData.getDatabase("local");
    MongoCollection<Document> collection = database.getCollection("leads");
    long count = collection.count(parse("{_id: {$eq: \"" + leadId + "\"}}"));
    assertEquals(1, count);
}
项目:twitter-stuff    文件:StatusUtils.java   
public static void saveFailureStatusProcesssed(MongoDatabase mongoDatabase, long id, boolean processed) {
    MongoCollection<Document> failureCollection = mongoDatabase.getCollection("failures");
    failureCollection.replaceOne(
            Filters.eq("tweet_id", id),
            new Document().append("tweet_id", id).append("processed", processed),
            new UpdateOptions().upsert(true));
}
项目:mongodb-crud    文件:InsertDocumentsImpl.java   
/**
 * This method insert the more than one document at a time
 */
@Override
public void insertMultipleDocuments() {
    MongoDatabase db = null;
    MongoCollection collection = null;
    try {
        db = client.getDatabase(mongo.getDataBase());
        collection = db.getCollection(mongo.getSampleCollection());

        Document journal = new Document("item", "journal")
                .append("qty", 25).append("tags", asList("blank", "red"));

        Document journalSize = new Document("h", 14).append("w", 21)
                .append("uom", "cm");
        journal.put("size", journalSize);

        Document mat = new Document("item", "mat").append("qty", 85)
                .append("tags", singletonList("gray"));

        Document matSize = new Document("h", 27.9).append("w", 35.5)
                .append("uom", "cm");
        mat.put("size", matSize);

        Document mousePad = new Document("item", "mousePad").append("qty",
                25).append("tags", asList("gel", "blue"));

        Document mousePadSize = new Document("h", 19).append("w", 22.85)
                .append("uom", "cm");
        mousePad.put("size", mousePadSize);
        collection.insertMany(asList(journal, mat, mousePad));
        log.info("Multiple Document Insert Successfully...");
    } catch (MongoException | ClassCastException e) {
        log.error("Exception occurred while insert **Multiple Document** : " + e, e);
    }
}
项目:Mp3Bib    文件:Database.java   
private int getLargestID() throws NotConnectedException {
    try {
        MongoCollection<Document> collection = getCollection();
        if (collection.count() <= 0) {
            return 0;
        }
        int largestID = (int) collection.find().sort(Sorts.descending("internalDbID")).limit(1).first().get("internalDbID");
        return largestID;
    } catch (Exception e) {
        BackendprocessService.getInstance().logger.error("couldnt find largest id " + e.toString());
    }
    return 1;
}
项目:nectar-server    文件:AuthController.java   
@RequestMapping(NectarServerApplication.ROOT_PATH + "/auth/removeClient")
public ResponseEntity removeClient(@RequestParam(value = "token") String jwtRaw, @RequestParam(value = "uuid") String uuid,
                                   HttpServletRequest request) {
    ResponseEntity r = Util.verifyJWT(jwtRaw, request);
    if(r != null)
        return r;

    ManagementSessionToken token = ManagementSessionToken.fromJSON(Util.getJWTPayload(jwtRaw));
    if(token == null)
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid TOKENTYPE.");

    if(SessionController.getInstance().checkManagementToken(token)) {
        MongoCollection<Document> clients = NectarServerApplication.getDb().getCollection("clients");

        Document client = clients.find(Filters.eq("uuid", uuid)).first();

        if(client == null) // Check if the client exists
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Client not found in database.");

        if(!(client.getOrDefault("loggedInUser", "null").equals("null"))) { // Check if a user is currently signed into the client.
            NectarServerApplication.getLogger().warn("Attempted client deletion from " + request.getRemoteAddr() + ", a user is already signed into client " + uuid);
            return ResponseEntity.status(HttpStatus.CONFLICT).body("A user is currently signed into this client.");
        }

        if(SessionController.getInstance().sessions.containsKey(uuid)) { // Check if the client is currently online with a session open
            SessionController.getInstance().sessions.remove(uuid); // Remove the session and it's token
            NectarServerApplication.getLogger().info("Revoked token for " + uuid + ": client deleted");
        }

        clients.deleteOne(Filters.eq("uuid", uuid)); // Delete client from the MongoDB database

        NectarServerApplication.getEventLog().logEntry(EventLog.EntryLevel.NOTICE, "Deleted client " + uuid + ", traced from " + request.getRemoteAddr());
    } else {
        return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Token expired/not valid.");
    }

    return ResponseEntity.status(HttpStatus.NO_CONTENT).body("Success.");
}
项目:nectar-server    文件:AuthController.java   
protected static ResponseEntity checkUserAdmin(SessionToken token, MongoCollection<Document> users, Document doc) {
    // getString will throw an exception if the key is not present in the document
    String loggedInUser = doc.getString("loggedInUser");
    if(loggedInUser.equals("none")) {
        // No user is logged in
        throw new RuntimeException(); // Move to catch block
    }

    Document userDoc = users.find(Filters.eq("username", loggedInUser)).first();

    if(userDoc == null) { // We can't find the logged in user in the users database, strange
        NectarServerApplication.getLogger().warn("Failed to find logged in user \"" + loggedInUser + "\" for session "
                + token.getUuid() + " while processing user registration"
        );
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to find current logged in user in DB.");
    } else { // User found, check admin now
        if(!userDoc.getBoolean("admin", false)) {
            NectarServerApplication.getLogger().warn("ATTEMPTED CLIENT REGISTRATION BY NON_ADMIN USER \"" + loggedInUser + "\""
                    + " from session " + token.getUuid()
            );

            NectarServerApplication.getEventLog().addEntry(EventLog.EntryLevel.WARNING, "A non-admin user attempted to register a client from " + token.getUuid());
            throw new RuntimeException(); // Move to catch block
        }
        // User is confirmed logged in and admin, all checks passed.
    }
    return null;
}
项目:rocketmq-flink-plugin    文件:MongoManager.java   
/**
 * @param dbName         库名
 * @param collectionName 表名
 * @param json1          条件
 * @param json2          保存doc
 * @return 更新结果信息
 */
public JSONObject executeUpdate(String dbName, String collectionName, JSONObject json1, JSONObject json2) {
    JSONObject resp = new JSONObject();
    try {
        MongoDatabase db = mongoClient.getDatabase(dbName);
        MongoCollection coll = db.getCollection(collectionName);
        JSONObject saveJson = new JSONObject();
        saveJson.put("$set", json2);
        Document doc1 = Document.parse(json1.toString());
        Document doc2 = Document.parse(saveJson.toString());
        UpdateResult ur = coll.updateOne(doc1, doc2);
        System.out.println("doc1 = " + doc1.toString());
        System.out.println("doc2 = " + doc2.toString());
        if (ur.isModifiedCountAvailable()) {
            if (json1.containsKey(ID)) {
                resp.put("Data", json1.get(ID));
            } else {
                resp.put("Data", json1);
            }
        }
    } catch (MongoTimeoutException e1) {
        e1.printStackTrace();
        resp.put("ReasonMessage", e1.getClass() + ":" + e1.getMessage());
        return resp;
    } catch (Exception e) {
        e.printStackTrace();
        resp.put("ReasonMessage", e.getClass() + ":" + e.getMessage());
    }
    return resp;
}
项目:nectar-server    文件:QueryController.java   
@SuppressWarnings("unchecked")
@RequestMapping(NectarServerApplication.ROOT_PATH + "/query/queryUsers")
public ResponseEntity queryUsers(@RequestParam(value = "token") String jwtRaw, HttpServletRequest request) {
    ManagementSessionToken token = ManagementSessionToken.fromJSON(Util.getJWTPayload(jwtRaw));
    if(token == null)
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Invalid TOKENTYPE.");

    if(!SessionController.getInstance().checkManagementToken(token)) {
        return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Token expired/not valid.");
    }

    JSONObject returnJSON = new JSONObject();

    MongoCollection<Document> clients = NectarServerApplication.getDb().getCollection("clients");
    MongoCollection<Document> users = NectarServerApplication.getDb().getCollection("users");
    users.find().forEach((Block<Document>) document -> {
        String username = document.getString("username");
        boolean admin = document.getBoolean("admin", false);

        JSONObject userJSON = new JSONObject();
        userJSON.put("admin", admin);

        Document clientDoc = clients.find(Filters.eq("loggedInUser", username)).first();
        if(clientDoc == null) {
            userJSON.put("signedIn", false);
        } else {
            userJSON.put("signedIn", true);
        }

        returnJSON.put(username, userJSON);
    });

    return ResponseEntity.ok(returnJSON.toJSONString());
}
项目:dooo    文件:SimpleMongodbAccessor.java   
/**
 * 批量插入数据
 */
public void batchInsert(String collectionName, List<Map<String, Object>> list) {
    MongoCollection collection = mongoDatabase.getCollection(collectionName);
    List<Document> documents = new ArrayList<>();
    for (Map<String, Object> map : list) {
        documents.add(new Document(map));
    }
    collection.insertMany(documents);
}
项目:nectar-server    文件:ClientSession.java   
public void updateState(ClientState state) {
    NectarServerApplication.getLogger().info("Client " + token.getUuid() + " state updated to: " + state.toString());
    this.state = state;

    MongoCollection<Document> clients = NectarServerApplication.getDb().getCollection("clients");
    clients.updateOne(Filters.eq("uuid", token.getUuid()),
            new Document("$set", new Document("state", state.toInt())));
}
项目:digital-display-garden-iteration-3-sixguysburgers-fries    文件:ExcelParser.java   
public static void setLiveUploadId(String uploadID){

        MongoClient mongoClient = new MongoClient();
        MongoDatabase test = mongoClient.getDatabase("test");
        MongoCollection configCollection = test.getCollection("config");

        configCollection.deleteMany(exists("liveUploadId"));
        configCollection.insertOne(new Document().append("liveUploadId", uploadID));
    }