当前位置: 首页>>代码示例>>Java>>正文


Java DBCollection类代码示例

本文整理汇总了Java中com.mongodb.DBCollection的典型用法代码示例。如果您正苦于以下问题:Java DBCollection类的具体用法?Java DBCollection怎么用?Java DBCollection使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


DBCollection类属于com.mongodb包,在下文中一共展示了DBCollection类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: getNextId

import com.mongodb.DBCollection; //导入依赖的package包/类
public int getNextId(GridFS destDatabase) {
	DBCollection countersCollection = destDatabase.getDB().getCollection("counters");

	DBObject record = countersCollection.findOne(new BasicDBObject("_id", "package"));
	if (record == null) {
		BasicDBObject dbObject = new BasicDBObject("_id", "package");
		dbObject.append("seq", 0);
		countersCollection.insert(dbObject);
		record = dbObject;
	}
	int oldID = (int) record.get("seq");
	int newID = oldID + 1;
	record.put("seq", newID);
	countersCollection.update(new BasicDBObject("_id", "package"), record);
	
	return newID;
}
 
开发者ID:roscisz,项目名称:KernelHive,代码行数:18,代码来源:DataManager.java

示例2: updateUserChangeNameAndSurnametoName

import com.mongodb.DBCollection; //导入依赖的package包/类
/**
 * update 6: {@link UserDocument} has changed; 'name' and 'surname' will be concat to 'name'.
 * for each every user document get 'name' and 'surname', concat them, update 'name', remove field surname and update document.
 *
 * @since V7
 */
@ChangeSet(order = "008", id = "updateUserChangeNameAndSurnameToName", author = "admin")
public void updateUserChangeNameAndSurnametoName(final MongoTemplate template) {
  final DBCollection userCollection = template.getCollection("user");

  final Iterator<DBObject> cursor = userCollection.find();
  while (cursor.hasNext()) {
    final DBObject current = cursor.next();

    final Object nameObj = current.get("name");
    final Object surnameObj = current.get("surname");
    final String updateName = (nameObj != null ? nameObj.toString() : "") + " " + (surnameObj != null ? surnameObj.toString() : "");

    final BasicDBObject updateQuery = new BasicDBObject();
    updateQuery.append("$set", new BasicDBObject("name", updateName));
    updateQuery.append("$unset", new BasicDBObject("surname", ""));

    final BasicDBObject searchQuery = new BasicDBObject();
    searchQuery.put("_id", current.get("_id"));

    userCollection.update(searchQuery, updateQuery);
  }
}
 
开发者ID:nkolytschew,项目名称:mongobee_migration_example,代码行数:29,代码来源:DatabaseChangeLog.java

示例3: afterCreate

import com.mongodb.DBCollection; //导入依赖的package包/类
/** Read the occasions that are stored in the database and schedule them to run. */
@PostConstruct
public void afterCreate() {
  String method = "afterCreate";
  logger.entering(clazz, method);

  orchestrator.setOccasionResource(this);

  DBCollection occasions = getCollection();
  DBCursor cursor = occasions.find();
  while (cursor.hasNext()) {
    DBObject dbOccasion = cursor.next();
    Occasion occasion = new Occasion(dbOccasion);
    try {
      // TODO: There was a comment here about how we should mark the event as
      //       popped in the database, which will have different meaning for
      //       one-time or interval occasions.  Need to re-visit this.
      orchestrator.scheduleOccasion(occasion);
    } catch (Throwable t) {
      logger.log(Level.WARNING, "Could not schedule occasion at startup", t);
    }
  }

  logger.exiting(clazz, method);
}
 
开发者ID:OpenLiberty,项目名称:sample-acmegifts,代码行数:26,代码来源:OccasionResource.java

示例4: selectOne

import com.mongodb.DBCollection; //导入依赖的package包/类
public DBObject selectOne(DBCollection collection) {
	DBObject fields = getFields();
	DBObject query = getQuery();
	DBObject orderByObject = getOrderByObject();

	// 日志
	log(fields, query, orderByObject);

	if (null == fields && null == orderByObject) {
		return collection.findOne(query);
	} else if (null != fields && null == orderByObject) {
		return collection.findOne(query, fields);
	} else {
		return collection.findOne(query, fields, orderByObject);
	}
}
 
开发者ID:xsonorg,项目名称:tangyuan2,代码行数:17,代码来源:SelectVo.java

示例5: initialize

import com.mongodb.DBCollection; //导入依赖的package包/类
/**
 * Init registry.
 **/
@PostConstruct
public void initialize() {
    Assert.notNull(this.mongoTemplate);

    LOGGER.debug("Setting up MongoDb Ticket Registry instance [{}]", this.collectionName);
    if (this.dropCollection) {
        LOGGER.debug("Dropping database collection: [{}]", this.collectionName);
        this.mongoTemplate.dropCollection(this.collectionName);
    }

    if (!this.mongoTemplate.collectionExists(this.collectionName)) {
        LOGGER.debug("Creating database collection: [{}]", this.collectionName);
        this.mongoTemplate.createCollection(this.collectionName);
    }
    LOGGER.debug("Creating indices on collection [{}] to auto-expire documents...", this.collectionName);
    final DBCollection collection = mongoTemplate.getCollection(this.collectionName);
    collection.createIndex(new BasicDBObject(TicketHolder.FIELD_NAME_EXPIRE_AT, 1),
            new BasicDBObject("expireAfterSeconds", 0));

    LOGGER.info("Configured MongoDb Ticket Registry instance [{}]", this.collectionName);
}
 
开发者ID:mrluo735,项目名称:cas-5.1.0,代码行数:25,代码来源:MongoDbTicketRegistry.java

示例6: doBatchUpdate

import com.mongodb.DBCollection; //导入依赖的package包/类
private int doBatchUpdate(DBCollection dbCollection, String collName, Collection<BatchUpdateOptions> options,
		boolean ordered) {
	DBObject command = new BasicDBObject();
	command.put("update", collName);
	List<BasicDBObject> updateList = new ArrayList<BasicDBObject>();
	for (BatchUpdateOptions option : options) {
		BasicDBObject update = new BasicDBObject();
		update.put("q", option.getQuery().getQueryObject());
		update.put("u", option.getUpdate().getUpdateObject());
		update.put("upsert", option.isUpsert());
		update.put("multi", option.isMulti());
		updateList.add(update);
	}
	command.put("updates", updateList);
	command.put("ordered", ordered);
	CommandResult commandResult = dbCollection.getDB().command(command);
	return Integer.parseInt(commandResult.get("n").toString());
}
 
开发者ID:shenan4321,项目名称:BIMplatform,代码行数:19,代码来源:AbstractBaseMongoDao.java

示例7: InsertData

import com.mongodb.DBCollection; //导入依赖的package包/类
private int InsertData(SQLInsertStatement state) {
	if (state.getValues().getValues().size() ==0 ){
		throw new RuntimeException("number of  columns error");
	}		
	if (state.getValues().getValues().size() != state.getColumns().size()){
		throw new RuntimeException("number of values and columns have to match");
	}
	SQLTableSource table=state.getTableSource();
	BasicDBObject o = new BasicDBObject();
	int i=0;
	for(SQLExpr col : state.getColumns()) {
		o.put(getFieldName2(col), getExpValue(state.getValues().getValues().get(i)));
		i++;
	}		
	DBCollection coll =this._db.getCollection(table.toString());
	coll.insert(new DBObject[] { o });
	return 1;
}
 
开发者ID:huang-up,项目名称:mycat-src-1.6.1-RELEASE,代码行数:19,代码来源:MongoSQLParser.java

示例8: UpData

import com.mongodb.DBCollection; //导入依赖的package包/类
private int UpData(SQLUpdateStatement state) {
	SQLTableSource table=state.getTableSource();
	DBCollection coll =this._db.getCollection(table.toString());
	
	SQLExpr expr=state.getWhere();
	DBObject query = parserWhere(expr);
	
	BasicDBObject set = new BasicDBObject();
	for(SQLUpdateSetItem col : state.getItems()){
		set.put(getFieldName2(col.getColumn()), getExpValue(col.getValue()));	
	}
	DBObject mod = new BasicDBObject("$set", set);
	coll.updateMulti(query, mod);
	//System.out.println("changs count:"+coll.getStats().size());
	return 1;		
}
 
开发者ID:huang-up,项目名称:mycat-src-1.6.1-RELEASE,代码行数:17,代码来源:MongoSQLParser.java

示例9: addUsers

import com.mongodb.DBCollection; //导入依赖的package包/类
@ChangeSet(order = "01",
           author = "developer",
           id = "01-addUsers")
public void addUsers(final DB db) {
    final DBCollection userCollection = db.getCollection(User.COLLECTION_NAME);

    userCollection.insert(BasicDBObjectBuilder
                                  .start()
                                  .add(FIELD_NAME_ID, new ObjectId("590f86d92449343841cc2c3f"))
                                  .add(User.FIELD_NAME_FIRST_NAME, "User")
                                  .add(User.FIELD_NAME_LAST_NAME, "One")
                                  .add(User.FIELD_NAME_EMAIL, "[email protected]")
                                  .get());

    userCollection.insert(BasicDBObjectBuilder
                                  .start()
                                  .add(FIELD_NAME_ID, new ObjectId("590f86d92449343841cc2c40"))
                                  .add(User.FIELD_NAME_FIRST_NAME, "User")
                                  .add(User.FIELD_NAME_LAST_NAME, "Two")
                                  .add(User.FIELD_NAME_EMAIL, "[email protected]")
                                  .get());
}
 
开发者ID:karlkyck,项目名称:spring-boot-completablefuture,代码行数:23,代码来源:InitialSetupMigration.java

示例10: testFindOne

import com.mongodb.DBCollection; //导入依赖的package包/类
public void testFindOne() throws UnknownHostException {
	MarcMongodbClient client = new MarcMongodbClient("localhost" , 27017, "sub_last_print");
	DBCollection collection = client.getCollection("marc");
	BasicDBObject doc = createTestObject();
	collection.insert(doc);
	assertEquals(1, collection.count());
	DBObject myDoc = collection.findOne();
	assertEquals("MongoDB", myDoc.get("name"));
	assertEquals("database", myDoc.get("type"));
	assertEquals(1, myDoc.get("count"));
	assertEquals(BasicDBObject.class, myDoc.get("info").getClass());
	assertEquals(new BasicDBObject("x", 203).append("y", 102), myDoc.get("info"));
	assertEquals(203, ((BasicDBObject)myDoc.get("info")).get("x"));
	assertEquals(Integer.class, ((BasicDBObject)myDoc.get("info")).get("x").getClass());
	System.out.println(myDoc);
	collection.remove(new BasicDBObject("name", "MongoDB"));
}
 
开发者ID:pkiraly,项目名称:metadata-qa-marc,代码行数:18,代码来源:MarcMongodbClientTest.java

示例11: testImport

import com.mongodb.DBCollection; //导入依赖的package包/类
public synchronized void testImport() throws URISyntaxException, IOException, InterruptedException {
	MarcMongodbClient client = new MarcMongodbClient("localhost" , 27017, "sub_last_print");
	DBCollection collection = client.getCollection("marc");
	assertEquals(0, collection.count());
	boolean insert = true;
	if (insert) {
		JsonPathCache<? extends XmlFieldInstance> cache;
		List<String> records = FileUtils.readLines("general/marc.json");
		for (String record : records) {
			cache = new JsonPathCache<>(record);
			Object jsonObject = jsonProvider.parse(record);
			String id   = cache.get("$.controlfield.[?(@.tag == '001')].content").get(0).getValue();
			String x003 = cache.get("$.controlfield.[?(@.tag == '003')].content").get(0).getValue();

			BasicDBObject doc = new BasicDBObject("type", "marcjson")
				.append("id", id)
				.append("x003", x003)
				.append("record", record);
			collection.insert(doc);
		}
		assertEquals(674, collection.count());
	}
	collection.remove(new BasicDBObject("type", "marcjson"));
	assertEquals(0, collection.count());
}
 
开发者ID:pkiraly,项目名称:metadata-qa-marc,代码行数:26,代码来源:MarcMongodbClientTest.java

示例12: selectVar

import com.mongodb.DBCollection; //导入依赖的package包/类
public Object selectVar(String dsKey, String sql) {
	SelectVo selectVo = (SelectVo) sqlParser.parse(sql);
	DBCollection collection = MongoSupport.getCollection(dsKey, selectVo.getTable());
	// return selectVo.selectVar(collection); fix bug
	Object result = selectVo.selectVar(collection);
	if (null == result) {
		return result;
	}
	if (result instanceof DBObject) {
		// return getXCOResults((DBObject) result, null);
		XCO one = getXCOResults((DBObject) result, null);
		return selectVo.selectVarOneField(one);
	} else {
		return result;
	}
}
 
开发者ID:xsonorg,项目名称:tangyuan2,代码行数:17,代码来源:MongoActuator.java

示例13: insert

import com.mongodb.DBCollection; //导入依赖的package包/类
public Object insert(DBCollection collection, WriteConcern writeConcern) {
	DBObject document = new BasicDBObject();
	// 匹配_id
	for (int i = 0, n = columns.size(); i < n; i++) {
		// document.put(columns.get(i), values.get(i).getValue());

		String tempColumn = columns.get(i);
		if (3 == tempColumn.length() && tempColumn.equals("_id")) {
			document.put(tempColumn, new ObjectId(values.get(i).getValue().toString()));
		} else {
			document.put(tempColumn, values.get(i).getValue());
		}
	}
	log(document);
	// TODO: WriteConcern.ACKNOWLEDGED需要可以配置
	// WriteResult result = collection.insert(document, WriteConcern.ACKNOWLEDGED);
	// collection.insert(document, MongoComponent.getInstance().getDefaultWriteConcern());
	collection.insert(document, writeConcern);
	Object oid = document.get("_id");
	if (null != oid) {
		return oid.toString();
	}
	return null;
}
 
开发者ID:xsonorg,项目名称:tangyuan2,代码行数:25,代码来源:InsertVo.java

示例14: updatePojoTest

import com.mongodb.DBCollection; //导入依赖的package包/类
@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);
}
 
开发者ID:axelspringer,项目名称:polymorphia,代码行数:25,代码来源:UpdateTest.java

示例15: createDatabase

import com.mongodb.DBCollection; //导入依赖的package包/类
public DB createDatabase(String databaseName) throws MongoServiceException {
		try {
			DB db = client.getDB(databaseName);
			
			// save into a collection to force DB creation.
			DBCollection col = db.createCollection("foo", null);
			BasicDBObject obj = new BasicDBObject();
			obj.put("foo", "bar");
			col.insert(obj);
			// drop the collection so the db is empty
//			col.drop();
			
			return db; 
		} catch (MongoException e) {
			// try to clean up and fail
			try {
				deleteDatabase(databaseName);
			} catch (MongoServiceException ignore) {}
			throw handleException(e);
		}
	}
 
开发者ID:cf-platform-eng,项目名称:mongodb-broker,代码行数:22,代码来源:MongoAdminService.java


注:本文中的com.mongodb.DBCollection类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。