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


Java MongoCollection類代碼示例

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


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

示例1: findOne

import com.mongodb.client.MongoCollection; //導入依賴的package包/類
/**
 * 查詢一個
 *
 * @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;
}
 
開發者ID:wxz1211,項目名稱:dooo,代碼行數:34,代碼來源:MongodbDataAccess.java

示例2: deleteManyDocument

import com.mongodb.client.MongoCollection; //導入依賴的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

示例3: updateDocumentWithCurrentDate

import com.mongodb.client.MongoCollection; //導入依賴的package包/類
/**
 * 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);
	}
}
 
開發者ID:sundarcse1216,項目名稱:mongodb-crud,代碼行數:23,代碼來源:UpdateDocumentsImpl.java

示例4: successfulInputOfComment

import com.mongodb.client.MongoCollection; //導入依賴的package包/類
@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"));
  }
 
開發者ID:UMM-CSci-3601-S17,項目名稱:digital-display-garden-iteration-4-dorfner-v2,代碼行數:26,代碼來源:TestPlantComment.java

示例5: testInsert

import com.mongodb.client.MongoCollection; //導入依賴的package包/類
@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();
    }
}
 
開發者ID:sap-nocops,項目名稱:Jerkoff,代碼行數:22,代碼來源:MongoTest.java

示例6: findAll

import com.mongodb.client.MongoCollection; //導入依賴的package包/類
/**
 * 查詢
 *
 * @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;
}
 
開發者ID:wxz1211,項目名稱:dooo,代碼行數:30,代碼來源:MongodbDataAccess.java

示例7: incrementMetadata

import com.mongodb.client.MongoCollection; //導入依賴的package包/類
@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));
}
 
開發者ID:UMM-CSci-3601-S17,項目名稱:digital-display-garden-iteration-3-sixguysburgers-fries,代碼行數:23,代碼來源:UnorganizedTests.java

示例8: deleteById

import com.mongodb.client.MongoCollection; //導入依賴的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

示例9: insertReport

import com.mongodb.client.MongoCollection; //導入依賴的package包/類
/**
 * 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
}
 
開發者ID:Labas-Vakaras,項目名稱:Smart_City,代碼行數:24,代碼來源:ReportDAO.java

示例10: Repository

import com.mongodb.client.MongoCollection; //導入依賴的package包/類
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);
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:19,代碼來源:Repositories.java

示例11: AddFlowerRatingReturnsTrueWithValidJsonInput

import com.mongodb.client.MongoCollection; //導入依賴的package包/類
@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);
}
 
開發者ID:UMM-CSci-3601-S17,項目名稱:digital-display-garden-iteration-4-dorfner-v2,代碼行數:23,代碼來源:FlowerRating.java

示例12: insertCityItem

import com.mongodb.client.MongoCollection; //導入依賴的package包/類
/**
 *
 * @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";
    }
}
 
開發者ID:Labas-Vakaras,項目名稱:Smart_City,代碼行數:24,代碼來源:CityItemDAO.java

示例13: buildChecksumDir

import com.mongodb.client.MongoCollection; //導入依賴的package包/類
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);
    }
}
 
開發者ID:jython234,項目名稱:nectar-server,代碼行數:26,代碼來源:FTSController.java

示例14: countAction

import com.mongodb.client.MongoCollection; //導入依賴的package包/類
@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;

}
 
開發者ID:uavorg,項目名稱:uavstack,代碼行數:27,代碼來源:MongoDBDataStore.java

示例15: AddFlowerRatingReturnsTrueWithValidJsonInput

import com.mongodb.client.MongoCollection; //導入依賴的package包/類
@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"));
}
 
開發者ID:UMM-CSci-3601-S17,項目名稱:digital-display-garden-iteration-4-revolverenguardia-1,代碼行數:21,代碼來源:FlowerRating.java


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