Java Code Examples for com.mongodb.DBCollection#update()

The following examples show how to use com.mongodb.DBCollection#update() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ReachablesProjectionUpdate.java    From act with GNU General Public License v3.0 6 votes vote down vote up
public void updateDatabase(DBCollection reachables) {
  for (String product : products) {
    // The query object for this product
    BasicDBObject newProductQuery = new BasicDBObject().append(INCHI_KEY, product);

    // DB list of the substrates of this projection
    BasicDBList substrateList = new BasicDBList();
    substrateList.addAll(substrates);

    // DB list of the one RO associated with this projection
    BasicDBList roList = new BasicDBList();
    roList.addAll(ros);

    // The full entry to be added to the product's precursor list
    BasicDBObject precursorEntry = new BasicDBObject()
        .append(SUBSTRATES_KEY, substrateList)
        .append(RO_KEY, roList);

    // The command to push the precursor entry onto the precursor list
    BasicDBObject precursors = new BasicDBObject();
    precursors.append("$push", new BasicDBObject(PRECURSOR_KEY, precursorEntry));

    // Do the update!
    reachables.update(newProductQuery, precursors, UPSERT, NO_MULTI);
  }
}
 
Example 2
Source File: PrivateStorageRepository.java    From konker-platform with Apache License 2.0 6 votes vote down vote up
public PrivateStorage update(String collectionName,  Map<String, Object> content) throws JsonProcessingException {
    DBObject queryById = new BasicDBObject().append(ID, content.get(ID));

    DBCollection collectionFor = mongoPrivateStorageTemplate.getCollection(collectionName);
    DBObject dbObject = collectionFor.findOne(queryById);

    if (!Optional.ofNullable(dbObject).isPresent()) {
        return null;
    }

    content.remove("_id");
    dbObject.putAll(content);

 DBObject query = new BasicDBObject().append(ID, dbObject.get(ID));

    DBCollection collection = mongoPrivateStorageTemplate.getCollection(collectionName);
    collection.update(query, dbObject);

    return PrivateStorage.builder()
            .collectionName(collectionName)
            .collectionContent(jsonParsingService.toJsonString(dbObject.toMap()))
            .build();
}
 
Example 3
Source File: Presence.java    From XBDD with Apache License 2.0 6 votes vote down vote up
@POST
@Path("/{product}/{major}.{minor}.{servicePack}/{build}/{featureId}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response addPresence(@BeanParam final Coordinates coordinates, @PathParam("featureId") final String featureId) {
	final DBCollection collection = this.mongoLegacyDb.getCollection("presence");
	final BasicDBObject query = new BasicDBObject("coordinates",
			coordinates.getObject(Field.PRODUCT, Field.VERSION, Field.BUILD).append(
					"featureId", featureId))
							.append("_id", coordinates.getProduct() + "/" + coordinates.getVersionString() + "/" + coordinates
									.getBuild() + "/" + featureId);
	final Date now = Calendar.getInstance().getTime();
	collection.update(query,
			new BasicDBObject("$set",
					new BasicDBObject("users." + LoggedInUserUtil.getLoggedInUser().getDisplay(), now).append("lastUpdated", now)),
			true,
			false);
	final DBObject newPresence = collection.findOne(query);
	newPresence.put("currentUser", LoggedInUserUtil.getLoggedInUser().getDisplay());
	return Response.ok(SerializerUtil.serialise(newPresence)).build();
}
 
Example 4
Source File: Presence.java    From XBDD with Apache License 2.0 6 votes vote down vote up
@DELETE
@Path("/{product}/{major}.{minor}.{servicePack}/{build}/{featureId}")
@Produces(MediaType.APPLICATION_JSON)
public Response deletePresence(@BeanParam final Coordinates coordinates, @PathParam("featureId") final String featureId) {
	final DBCollection collection = this.mongoLegacyDb.getCollection("presence");
	final BasicDBObject query = new BasicDBObject("coordinates",
			coordinates.getObject(Field.PRODUCT, Field.VERSION, Field.BUILD).append(
					"featureId", featureId))
							.append("_id", coordinates.getProduct() + "/" + coordinates.getVersionString() + "/" + coordinates
									.getBuild() + "/" + featureId);
	collection.update(query,
			new BasicDBObject("$unset", new BasicDBObject("users." + LoggedInUserUtil.getLoggedInUser().getDisplay(), 1)),
			true, false);
	final DBObject newPresence = collection.findOne(query);
	newPresence.put("currentUser", LoggedInUserUtil.getLoggedInUser().getDisplay());
	return Response.ok(SerializerUtil.serialise(newPresence)).build();
}
 
Example 5
Source File: Favourites.java    From XBDD with Apache License 2.0 6 votes vote down vote up
private void setPinStateOfBuild(final String product,
		final String version,
		final String build,
		final boolean state) {

	final DBCollection collection = this.mongoLegacyDb.getCollection("summary");

	final BasicDBObject query = new BasicDBObject("_id", product + "/" + version);
	final BasicDBObject toBePinned = new BasicDBObject("pinned", build);
	final String method;

	if (state) {
		method = "$addToSet";
	} else {
		method = "$pull";
	}

	collection.update(query, new BasicDBObject(method, toBePinned));
}
 
Example 6
Source File: MongoDBUtil.java    From gameserver with Apache License 2.0 6 votes vote down vote up
/**
 *  Save i.e. INSERT or UPDATE an object to mongodb.
 *  
 * @param query usually the _id of collection, which is byte[] , null means insert a new row
 * @param objectToSave the object to save
 * @param databaseName the database
 * @param namespace the namespace, maybe null
 * @param isSafeWrite whether to enable the SafeWrite mode
 */
public static final void saveToMongo(DBObject query, DBObject objectToSave, 
		String databaseName, String namespace, String collection, boolean isSafeWrite) {

	DBCollection coll = getDBCollection(databaseName, namespace, collection);
	if ( isSafeWrite ) {
		if ( query == null ) {
			coll.insert(objectToSave);
		} else {
			coll.update(query, objectToSave, true, false, WriteConcern.SAFE);
		}
	} else {
		if ( query == null ) {
			coll.insert(objectToSave);
		} else {
			coll.update(query, objectToSave, true, false, WriteConcern.NONE);
		}
	}
}
 
Example 7
Source File: BuildReOrdering.java    From XBDD with Apache License 2.0 5 votes vote down vote up
@PUT
@Path("/{product}/{major}.{minor}.{servicePack}")
@Consumes(MediaType.APPLICATION_JSON)
public Response setBuildOrderForProductVersion(@BeanParam final Coordinates coordinates,
		final Builds json) {
	final DBCollection summaryCollection = this.mongoLegacyDb.getCollection("summary");
	final BasicDBObject query = new BasicDBObject("_id", coordinates.getProduct() + "/" + coordinates.getVersionString());
	summaryCollection.update(query, new BasicDBObject("$set", new BasicDBObject("builds", json.builds)));

	return Response.ok().build();
}
 
Example 8
Source File: Recents.java    From XBDD with Apache License 2.0 5 votes vote down vote up
@PUT
@Path("/feature/{product}/{major}.{minor}.{servicePack}/{build}/{id:.+}")
@Produces(MediaType.APPLICATION_JSON)
public Response addFeatureToRecents(@QueryParam("name") final String featureName,
		@BeanParam final Coordinates coordinates,
		@PathParam("id") final String featureID) {

	final BasicDBObject featureDetails = new BasicDBObject("name", featureName);
	featureDetails.put("product", coordinates.getProduct());
	featureDetails.put("version", coordinates.getVersionString());
	featureDetails.put("build", coordinates.getBuild());
	featureDetails.put("id", featureID);

	final DBCollection collection = this.mongoLegacyDb.getCollection("users");

	final BasicDBObject user = new BasicDBObject();
	user.put("user_id", LoggedInUserUtil.getLoggedInUser().getUserId());

	final DBObject blank = new BasicDBObject();
	final DBObject doc = collection.findAndModify(user, blank, blank, false, new BasicDBObject("$set", user), true, true);

	if (doc.containsField("recentFeatures")) {
		final BasicDBList featureArray = (BasicDBList) doc.get("recentFeatures");
		if (featureArray.contains(featureDetails)) {
			featureArray.remove(featureDetails);
			featureArray.add(featureDetails);
			collection.update(user, new BasicDBObject("$set", new BasicDBObject("recentFeatures", featureArray)));
		} else {
			if (featureArray.size() >= 5) {
				collection.update(user, new BasicDBObject("$pop", new BasicDBObject("recentFeatures", "-1")));
			}
			collection.update(user, new BasicDBObject("$addToSet", new BasicDBObject("recentFeatures", featureDetails)));
		}
	} else {
		collection.update(user, new BasicDBObject("$addToSet", new BasicDBObject("recentFeatures", featureDetails)));
	}

	return Response.ok().build();
}
 
Example 9
Source File: Recents.java    From XBDD with Apache License 2.0 5 votes vote down vote up
@PUT
@Path("/build/{product}/{major}.{minor}.{servicePack}/{build}")
@Produces(MediaType.APPLICATION_JSON)
public Response addBuildToRecents(@BeanParam final Coordinates coordinates) {

	final DBObject buildCoords = coordinates.getReportCoordinates();

	final DBCollection collection = this.mongoLegacyDb.getCollection("users");

	final BasicDBObject user = new BasicDBObject();
	user.put("user_id", LoggedInUserUtil.getLoggedInUser().getUserId());

	final DBObject blank = new BasicDBObject();
	final DBObject doc = collection.findAndModify(user, blank, blank, false, new BasicDBObject("$set", user), true, true);

	if (doc.containsField("recentBuilds")) {
		final BasicDBList buildArray = (BasicDBList) doc.get("recentBuilds");
		if (buildArray.contains(buildCoords)) {
			// BasicDBObject toMove = (BasicDBObject) featureArray.get(featureArray.indexOf(featureDetails));
			buildArray.remove(buildCoords);
			buildArray.add(buildCoords);
			collection.update(user, new BasicDBObject("$set", new BasicDBObject("recentBuilds", buildArray)));
		} else {
			if (buildArray.size() >= 5) {
				collection.update(user, new BasicDBObject("$pop", new BasicDBObject("recentBuilds", "-1")));
			}
			collection.update(user, new BasicDBObject("$addToSet", new BasicDBObject("recentBuilds", buildCoords)));
		}
	} else {
		collection.update(user, new BasicDBObject("$addToSet", new BasicDBObject("recentBuilds", buildCoords)));
	}

	return Response.ok().build();
}
 
Example 10
Source File: Favourites.java    From XBDD with Apache License 2.0 5 votes vote down vote up
public void setFavouriteStateOfProduct(final String product, final boolean state) {

		final DBCollection collection = this.mongoLegacyDb.getCollection("users");

		final BasicDBObject user = new BasicDBObject();
		user.put("user_id", LoggedInUserUtil.getLoggedInUser().getUserId());

		final DBObject blank = new BasicDBObject();
		collection.findAndModify(user, blank, blank, false, new BasicDBObject("$set", user), true, true);

		// User exists
		final DBObject favourites = new BasicDBObject("favourites." + product, state);
		final DBObject update = new BasicDBObject("$set", favourites);
		collection.update(user, update);
	}
 
Example 11
Source File: MongoUtil.java    From gameserver with Apache License 2.0 5 votes vote down vote up
/**
 *  Save i.e. INSERT or UPDATE an object to mongodb.
 *  
 * @param query usually the _id of collection, which is byte[] 
 * @param objectToSave the object to save
 * @param databaseName the database
 * @param namespace the namespace, maybe null
 * @param isSafeWrite whether to enable the SafeWrite mode
 */
public static final void saveToMongo(DBObject query, DBObject objectToSave, 
		String databaseName, String namespace, String collection, boolean isSafeWrite) {
	
	DBCollection coll = getDBCollection(databaseName, namespace, collection);
	if ( isSafeWrite ) {
		coll.update(query, objectToSave, true, false, WriteConcern.SAFE);
	} else {
		coll.update(query, objectToSave, true, false, WriteConcern.NONE);
	}
}
 
Example 12
Source File: MongoBenchmark.java    From gameserver with Apache License 2.0 5 votes vote down vote up
public static void testBasicBson(int max, DB db) {
	String collName = "testbasicbson";
	DBCollection coll = db.getCollection(collName);
	
	//Setup a sharded collection
	BasicDBObject command = new BasicDBObject();
	command.put("shardcollection", collName);
	DBObject key = new BasicDBObject();
	key.put("_id", 1);
	command.put("key", key);
	command.put("unique", true);
	db.command(command);
	
	long startM = System.currentTimeMillis();
	BasicDBObject objKey = new BasicDBObject();
	UserId userId = new UserId("username");
	objKey.put("_id", userId.getInternal());
	
	BasicDBObject obj = new BasicDBObject();
	for ( int i=0; i<max; i++ ) {
		obj.put("_id", userId.getInternal());
		obj.put("test-"+(i)%10, "value-"+i);
		coll.update(objKey, obj, true, false);
	}
	long endM = System.currentTimeMillis();
	
	System.out.println(collName+ " update " + max + " my objectid. time: " + (endM-startM) + " benchmark(56273)");
	
	CommandResult result = db.getStats();
	System.out.println(result);
}
 
Example 13
Source File: MongoBenchmark.java    From gameserver with Apache License 2.0 5 votes vote down vote up
public static void testMapDBObject(int max, DB db) {
	String collName = "testmapobject";
	DBCollection coll = db.getCollection(collName);
	
	//Setup a sharded collection
	BasicDBObject command = new BasicDBObject();
	command.put("shardcollection", collName);
	DBObject key = new BasicDBObject();
	key.put("_id", 1);
	command.put("key", key);
	command.put("unique", true);
	db.command(command);
	
	long startM = System.currentTimeMillis();
	BasicDBObject objKey = new BasicDBObject();
	UserId userId = new UserId("username");
	objKey.put("_id", userId.getInternal());
	
	MapDBObject obj = new MapDBObject();
	for ( int i=0; i<max; i++ ) {
		obj.put("_id", userId.getInternal());
		obj.put("test-"+(i)%10, "value-"+i);
		coll.update(objKey, obj, true, false);
	}
	long endM = System.currentTimeMillis();
	
	System.out.println(collName+ " update " + max + " my objectid. time: " + (endM-startM) + " benchmark(114892)");
	
	CommandResult result = db.getStats();
	System.out.println(result);
}
 
Example 14
Source File: RollupStorageInterceptor.java    From hvdf with Apache License 2.0 5 votes vote down vote up
@Override
public void pushSample(DBObject sample, boolean isList, BasicDBList resultIds) {
	
	if(isList){
		
		// Use the batch API to send a number of samples
		updateBatch((BasicDBList)sample);			
	}
	else if(sample != null){
		
		// This is a document, place it straight in appropriate collection
		BasicDBObject doc = ((BasicDBObject) sample);
		long timestamp = this.rollupPeriod * (doc.getLong(Sample.TS_KEY) / this.rollupPeriod);			
		DBCollection collection = collectionAllocator.getCollection(timestamp);
		
		// Ask the id allocator for the query
		BasicDBObject query = this.idFactory.getQuery(sample.get(Sample.SOURCE_KEY), timestamp);
		
		// Build the update clause using the ops list
		BasicDBObject update = new BasicDBObject();
		for(RollupOperation rollupOp : this.rollupOps){
			
			DBObject updateClause = rollupOp.getUpdateClause(sample);
			
			// Check for top level operators that already exist so they dont overwrite
			for(String key : updateClause.keySet()){
				BasicDBObject existingClause = (BasicDBObject) update.get(key);
				if(existingClause != null){
					// Merge the arguments to the top level op
					existingClause.putAll((DBObject)updateClause.get(key));
				} else {
					update.put(key, updateClause.get(key));
				}
			}
		}
		
		collection.update(query, update, true, false);
	}
}
 
Example 15
Source File: MongoExample.java    From tutorials with MIT License 4 votes vote down vote up
public static void main(String[] args) {

        MongoClient mongoClient = new MongoClient("localhost", 27017);

        DB database = mongoClient.getDB("myMongoDb");

        // print existing databases
        mongoClient.getDatabaseNames().forEach(System.out::println);

        database.createCollection("customers", null);

        // print all collections in customers database
        database.getCollectionNames().forEach(System.out::println);

        // create data
        DBCollection collection = database.getCollection("customers");
        BasicDBObject document = new BasicDBObject();
        document.put("name", "Shubham");
        document.put("company", "Baeldung");
        collection.insert(document);

        // update data
        BasicDBObject query = new BasicDBObject();
        query.put("name", "Shubham");
        BasicDBObject newDocument = new BasicDBObject();
        newDocument.put("name", "John");
        BasicDBObject updateObject = new BasicDBObject();
        updateObject.put("$set", newDocument);
        collection.update(query, updateObject);

        // read data
        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.put("name", "John");
        DBCursor cursor = collection.find(searchQuery);
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }

        // delete data
        BasicDBObject deleteQuery = new BasicDBObject();
        deleteQuery.put("name", "John");
        collection.remove(deleteQuery);
    }