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