List of usage examples for com.mongodb DBCollection save
public WriteResult save(final DBObject document)
From source file:org.springframework.data.mongodb.crossstore.MongoChangeSetPersister.java
License:Apache License
public Object persistState(ChangeSetBacked entity, ChangeSet cs) throws DataAccessException { if (cs == null) { log.debug("Flush: changeset was null, nothing to flush."); return 0L; }//from w ww .j a v a2s . c o m if (log.isDebugEnabled()) { log.debug("Flush: changeset: {}", cs.getValues()); } String collName = getCollectionNameForEntity(entity.getClass()); if (mongoTemplate.getCollection(collName) == null) { mongoTemplate.createCollection(collName); } for (String key : cs.getValues().keySet()) { if (key != null && !key.startsWith("_") && !key.equals(ChangeSetPersister.ID_KEY)) { Object value = cs.getValues().get(key); final DBObject dbQuery = new BasicDBObject(); dbQuery.put(ENTITY_ID, getPersistentId(entity, cs)); dbQuery.put(ENTITY_CLASS, entity.getClass().getName()); dbQuery.put(ENTITY_FIELD_NAME, key); DBObject dbId = mongoTemplate.execute(collName, new CollectionCallback<DBObject>() { public DBObject doInCollection(DBCollection collection) throws MongoException, DataAccessException { return collection.findOne(dbQuery); } }); if (value == null) { if (log.isDebugEnabled()) { log.debug("Flush: removing: {}", dbQuery); } mongoTemplate.execute(collName, new CollectionCallback<Object>() { public Object doInCollection(DBCollection collection) throws MongoException, DataAccessException { collection.remove(dbQuery); return null; } }); } else { final DBObject dbDoc = new BasicDBObject(); dbDoc.putAll(dbQuery); if (log.isDebugEnabled()) { log.debug("Flush: saving: {}", dbQuery); } mongoTemplate.getConverter().write(value, dbDoc); dbDoc.put(ENTITY_FIELD_CLASS, value.getClass().getName()); if (dbId != null) { dbDoc.put("_id", dbId.get("_id")); } mongoTemplate.execute(collName, new CollectionCallback<Object>() { public Object doInCollection(DBCollection collection) throws MongoException, DataAccessException { collection.save(dbDoc); return null; } }); } } } return 0L; }
From source file:org.springframework.integration.mongodb.metadata.MongoDbMetadataStore.java
License:Apache License
/** * Store a metadata {@code value} under provided {@code key} to the configured * {@link #collectionName}./*from w ww. j a v a2s . c o m*/ * <p> * If a document does not exist with the specified {@code key}, the method performs an {@code insert}. * If a document exists with the specified {@code key}, the method performs an {@code update}. * @param key the metadata entry key * @param value the metadata entry value * @see MongoTemplate#execute(String, CollectionCallback) * @see DBCollection#save */ @Override public void put(String key, String value) { Assert.hasText(key, "'key' must not be empty."); Assert.hasText(value, "'value' must not be empty."); final Map<String, String> entry = new HashMap<String, String>(); entry.put(ID_FIELD, key); entry.put(VALUE, value); this.template.execute(this.collectionName, (CollectionCallback<Object>) new CollectionCallback<Object>() { @Override public Object doInCollection(DBCollection collection) throws MongoException, DataAccessException { return collection.save(new BasicDBObject(entry)); } }); }
From source file:org.vertx.java.busmods.persistor.MongoPersistor.java
License:Apache License
private void doSave(Message<JsonObject> message) { String collection = getMandatoryString("collection", message); if (collection == null) { return;/*from w w w . j av a 2s.co m*/ } JsonObject doc = getMandatoryObject("document", message); if (doc == null) { return; } String genID; if (doc.getField("_id") == null) { genID = UUID.randomUUID().toString(); doc.putString("_id", genID); } else { genID = null; } DBCollection coll = db.getCollection(collection); DBObject obj = jsonToDBObject(doc); coll.save(obj); if (genID != null) { JsonObject reply = new JsonObject(); reply.putString("_id", genID); sendOK(message, reply); } else { sendOK(message); } }
From source file:org.vertx.mods.MongoPersistor.java
License:Apache License
private void doSave(Message<JsonObject> message) { String collection = getMandatoryString("collection", message); if (collection == null) { return;// w w w.ja va 2 s.c o m } JsonObject doc = getMandatoryObject("document", message); if (doc == null) { return; } String genID; if (doc.getField("_id") == null) { genID = UUID.randomUUID().toString(); doc.putString("_id", genID); } else { genID = null; } DBCollection coll = db.getCollection(collection); DBObject obj = jsonToDBObject(doc); WriteResult res = coll.save(obj); if (res.getError() == null) { if (genID != null) { JsonObject reply = new JsonObject(); reply.putString("_id", genID); sendOK(message, reply); } else { sendOK(message); } } else { sendError(message, res.getError()); } }
From source file:org.wrml.contrib.runtime.service.mongo.MongoService.java
License:Apache License
@Override public Model save(final Model model) { final URI schemaUri = model.getSchemaUri(); final String collectionName = convertToCollectionName(schemaUri); final Keys keys = model.getKeys(); DBObject mongoKeys = createMongoKeys(keys); if (!_Mongo.collectionExists(collectionName)) { final DBCollection mongoCollection = _Mongo.getCollection(collectionName); final DBObject collectionIndex = new BasicDBObject(); final Set<String> indexKeySet = mongoKeys.keySet(); for (final String indexKey : indexKeySet) { collectionIndex.put(indexKey, 1); }/*from www . ja va2 s . c o m*/ final DBObject options = new BasicDBObject(); options.put("background", true); mongoCollection.ensureIndex(collectionIndex, options); } final DBObject mongoObject; try { mongoObject = convertToMongoObject(model); } catch (ModelWritingException e) { throw new ServiceException("Failed to convert WRML model instance to a mongoDB object.", e, this); } final DBCollection mongoCollection = _Mongo.getCollection(collectionName); if (mongoCollection == null) { // Should not happen final String logMessage = getConfiguration().getName() + " - Collection should exist. Name:\n" + collectionName; LOG.error(logMessage); throw new ServiceException(logMessage, null, this); } final DBObject existingMongoObject = mongoCollection.findOne(mongoKeys); if (existingMongoObject != null) { mongoObject.put("_id", existingMongoObject.get("_id")); } String errorMessage = null; Throwable throwable = null; try { final WriteResult mongoWriteResult = mongoCollection.save(mongoObject); errorMessage = mongoWriteResult.getError(); } catch (Throwable t) { errorMessage = t.getMessage(); throwable = t; } if (errorMessage != null || throwable != null) { final String logMessage = getConfiguration().getName() + " - Error saving model (" + errorMessage + ")."; LOG.error(logMessage); throw new ServiceException(logMessage, throwable, this); } // TODO: Should this return the saved model instead (using get?)? return model; }
From source file:org.xtext.mongobeans.examples.JavaExample.java
License:Open Source License
public void dealWithMongoEntities() throws UnknownHostException, MongoException { DBObject artist = new BasicDBObject(); artist.put("name", "John Coltrane"); DBObject album = new BasicDBObject(); album.put("title", "A Love Supreme"); album.put("year", 1965); List<DBObject> albums = new ArrayList<DBObject>(); artist.put("albums", albums); DB db = new Mongo().getDB("testdb"); DBCollection dbCollection = db.getCollection("testCollection"); dbCollection.save(artist); DBObject query = new BasicDBObject(); query.put("name", "John Coltrane"); DBObject artistFromDB = dbCollection.find(query).next(); Object albumFromDB = artistFromDB.get("album"); if (albumFromDB instanceof Collection) { Object firstAlbumFromDB = ((Collection<?>) album).iterator().next(); if (firstAlbumFromDB instanceof DBObject) { Object titleFromDB = album.get("title"); System.out.println(titleFromDB.toString()); }/*from ww w. j a v a2 s . c o m*/ } }
From source file:org.xtext.mongobeans.lib.MongoExtensions.java
License:Open Source License
public WriteResult save(final DBCollection collection, final IMongoBean wrapper) { DBObject _dbObject = wrapper.getDbObject(); WriteResult _save = collection.save(_dbObject); return _save; }
From source file:piecework.config.DataConfiguration.java
License:Educational Community License
private void importCollection(final DBCollection collection, final InputStream jsonStream) { @SuppressWarnings("unchecked") String entry = new Scanner(jsonStream).useDelimiter("\\A").next(); final List<DBObject> list = (List<DBObject>) JSON.parse(entry); LOG.debug("Have " + list.size() + " objects to load..."); // collection.insert(list); for (DBObject object : list) collection.save(object); }
From source file:piecework.repository.concrete.EmbeddedMongoInstance.java
License:Educational Community License
/** * Imports data into a collection/*from w ww.ja v a2 s .com*/ * * @param collection * @param jsonStream */ private void importCollection(final DBCollection collection, final InputStream jsonStream) { @SuppressWarnings("unchecked") final List<DBObject> list = (List<DBObject>) JSON.parse(new Scanner(jsonStream).useDelimiter("\\A").next()); LOG.debug("Have " + list.size() + " obejcts to load..."); // collection.insert(list); for (DBObject object : list) collection.save(object); }
From source file:rapture.sheet.mongodb.MongoCellStore.java
License:Open Source License
public void deleteColumn(final String sheetName, final int column) { final DBCollection collection = MongoDBFactory.getDB(instanceName).getCollection(tableName); MongoRetryWrapper<Object> wrapper = new MongoRetryWrapper<Object>() { public DBCursor makeCursor() { // Deleting a column is two things. // (a) find and remove all cells (in all dimensions) that have // this as a // column // (b) modify all cells that have a column > this column, // decreasing // their column by 1 BasicDBObject query = new BasicDBObject(); query.put(KEY, sheetName);// ww w .j a v a 2 s.c o m query.put(COL, column); collection.findAndRemove(query); BasicDBObject changeQuery = new BasicDBObject(); changeQuery.put(KEY, sheetName); BasicDBObject testQuery = new BasicDBObject(); testQuery.put("$gt", column); changeQuery.put(COL, testQuery); return collection.find(changeQuery); } public Object action(DBCursor cursor) { while (cursor.hasNext()) { BasicDBObject object = (BasicDBObject) cursor.next(); object.put(COL, object.getInt(COL) - 1); object.put(EPOCH, getLatestEpoch(sheetName, object.getInt(DIM))); collection.save(object); } return null; } }; @SuppressWarnings("unused") Object o = wrapper.doAction(); }