本文整理汇总了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;
}
示例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);
}
}
示例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);
}
示例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);
}
}
示例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);
}
示例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());
}
示例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;
}
示例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;
}
示例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());
}
示例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"));
}
示例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());
}
示例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;
}
}
示例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;
}
示例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);
}
示例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);
}
}