Java Code Examples for com.mongodb.client.MongoCollection#replaceOne()

The following examples show how to use com.mongodb.client.MongoCollection#replaceOne() . 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: UsersDao.java    From XBDD with Apache License 2.0 6 votes vote down vote up
public User saveUser(final User user) {
	final MongoCollection<User> users = getUsersColletions();
	final Bson query = Filters.eq("user_id", user.getUserId());

	final User savedUser = users.find(query).first();

	if (savedUser == null) {
		users.insertOne(user);

		return user;
	}

	if (!StringUtils.equals(savedUser.getDisplay(), user.getDisplay())) {
		savedUser.setDisplay(user.getDisplay());
		users.replaceOne(query, savedUser);
	}

	return savedUser;

}
 
Example 2
Source File: TagAssignmentDao.java    From XBDD with Apache License 2.0 6 votes vote down vote up
public void saveTagAssignment(final Coordinates coordinates, final SingleTagAssignment singleTagAssignment) {
	final MongoCollection<TagAssignments> tagAssignments = getTagAssignmentColletions();
	final CoordinatesDto coordinatesDto = CoordinatesMapper.mapCoordinates(coordinates);
	final Bson query = Filters.eq("coordinates", coordinatesDto);

	final TagAssignments savedAssignments = tagAssignments.find(query).first();

	if (savedAssignments == null) {
		final TagAssignments newAssignments = new TagAssignments();
		newAssignments.setCoordinates(coordinatesDto);
		newAssignments.setTags(Arrays.asList(singleTagAssignment));
		tagAssignments.insertOne(newAssignments);
	} else {
		savedAssignments.getTags().removeIf(single -> single.getTag().equals(singleTagAssignment.getTag()));
		savedAssignments.getTags().add(singleTagAssignment);
		tagAssignments.replaceOne(query, savedAssignments);
	}

}
 
Example 3
Source File: MongoDBFactory.java    From database-transform-tool with Apache License 2.0 6 votes vote down vote up
/**
 * @decription 更新数据
 * @author yi.zhang
 * @time 2017年6月2日 下午6:19:08
 * @param table	文档名称(表名)
 * @param obj
 * @return
 */
public int update(String table, Object obj) {
	try {
		if(session==null){
			init(servers, database, schema, username, password);
		}
		MongoCollection<Document> collection = session.getCollection(table);
		if (collection == null) {
			return 0;
		}
		JSONObject json = JSON.parseObject(JSON.toJSONString(obj));
		Document value = Document.parse(JSON.toJSONString(obj));
		collection.replaceOne(Filters.eq("_id", json.containsKey("_id")?json.get("_id"):json.get("id")), value);
		return 1;
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return -1;
}
 
Example 4
Source File: SummaryDao.java    From XBDD with Apache License 2.0 6 votes vote down vote up
public void updateSummary(final Coordinates coordinates) {
	final MongoCollection<Summary> summary = getSummaryCollection();

	final Bson query = Filters.eq(coordinates.getProduct() + "/" + coordinates.getVersionString());
	final Summary summaryObject = summary.find(query, Summary.class).first();

	if (summaryObject != null) { // lookup the summary document
		if (!summaryObject.getBuilds()
				.contains(coordinates.getBuild())) { // only update it if this build hasn't been added to it before.
			summaryObject.getBuilds().add(coordinates.getBuild());
			summary.replaceOne(query, summaryObject);
		}
	} else {
		final Summary newSummary = new Summary();
		newSummary.setId(coordinates.getProduct() + "/" + coordinates.getVersionString());
		newSummary.setBuilds(new ArrayList<>());
		newSummary.getBuilds().add(coordinates.getBuild());

		// Summary's don't care about the build as they have a list of them.
		final CoordinatesDto coordDto = CoordinatesMapper.mapCoordinates(coordinates);
		coordDto.setBuild(null);
		newSummary.setCoordinates(coordDto);

		summary.insertOne(newSummary);
	}
}
 
Example 5
Source File: LumongoIndex.java    From lumongo with Apache License 2.0 6 votes vote down vote up
private void storeIndexSettings() {
	indexLock.writeLock().lock();
	try {
		MongoDatabase db = mongo.getDatabase(mongoConfig.getDatabaseName());
		MongoCollection<Document> dbCollection = db.getCollection(indexConfig.getIndexName() + CONFIG_SUFFIX);
		Document settings = IndexConfigUtil.toDocument(indexConfig);
		settings.put(MongoConstants.StandardFields._ID, SETTINGS_ID);

		Document query = new Document();
		query.put(MongoConstants.StandardFields._ID, SETTINGS_ID);

		dbCollection.replaceOne(query, settings, new UpdateOptions().upsert(true));
	}
	finally {
		indexLock.writeLock().unlock();
	}

}
 
Example 6
Source File: MongoDirectory.java    From lumongo with Apache License 2.0 5 votes vote down vote up
@Override
public void updateFileMetadata(NosqlFile nosqlFile) throws IOException {
	MongoCollection<Document> c = getFilesCollection();

	Document query = new Document();
	query.put(FILE_NUMBER, nosqlFile.getFileNumber());

	Document object = toDocument(nosqlFile);
	c.replaceOne(query, object, new UpdateOptions().upsert(true));

}
 
Example 7
Source File: RenderDao.java    From render with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Saves the specified transform spec to the database.
 *
 * @param  stackId        stack identifier.
 * @param  transformSpec  specification to be saved.
 *
 * @throws IllegalArgumentException
 *   if any required parameters or transform spec references are missing.
 */
void saveTransformSpec(final StackId stackId,
                       final TransformSpec transformSpec)
        throws IllegalArgumentException {

    MongoUtil.validateRequiredParameter("stackId", stackId);
    MongoUtil.validateRequiredParameter("transformSpec", transformSpec);
    MongoUtil.validateRequiredParameter("transformSpec.id", transformSpec.getId());

    final MongoCollection<Document> transformCollection = getTransformCollection(stackId);

    final String context = "transform spec with id '" + transformSpec.getId() + "'";
    validateTransformReferences(context, stackId, transformSpec);

    final Document query = new Document();
    query.put("id", transformSpec.getId());

    final Document transformSpecObject = Document.parse(transformSpec.toJson());

    final UpdateResult result = transformCollection.replaceOne(query,
                                                               transformSpecObject,
                                                               MongoUtil.UPSERT_OPTION);

    LOG.debug("saveTransformSpec: {}.{},({}), upsertedId is {}",
              MongoUtil.fullName(transformCollection),
              MongoUtil.action(result),
              query.toJson(),
              result.getUpsertedId());
}
 
Example 8
Source File: MongoWrapper.java    From MongoDb-Sink-Connector with Apache License 2.0 5 votes vote down vote up
/**
 * Store a document in MongoDB. If the document has an ID, it will replace existing
 * documents with that ID. If it does not, it will be inserted and MongoDB will assign it with
 * a unique ID.
 *
 * @param topic Kafka topic that the document belongs to
 * @param doc MongoDB document
 * @throws MongoException if the document could not be stored.
 */
public void store(String topic, Document doc) throws MongoException {
    MongoCollection<Document> collection = getCollection(topic);
    Object mongoId = doc.get(MONGO_ID_KEY);
    if (mongoId != null) {
        collection.replaceOne(eq(MONGO_ID_KEY, mongoId), doc, UPDATE_UPSERT);
    } else {
        collection.insertOne(doc);
    }
}
 
Example 9
Source File: MongoStorage.java    From LuckPerms with MIT License 5 votes vote down vote up
@Override
public PlayerSaveResult savePlayerData(UUID uniqueId, String username) {
    username = username.toLowerCase();
    MongoCollection<Document> c = this.database.getCollection(this.prefix + "uuid");

    // find any existing mapping
    String oldUsername = getPlayerName(uniqueId);

    // do the insert
    if (!username.equalsIgnoreCase(oldUsername)) {
        c.replaceOne(new Document("_id", uniqueId), new Document("_id", uniqueId).append("name", username), new ReplaceOptions().upsert(true));
    }

    PlayerSaveResultImpl result = PlayerSaveResultImpl.determineBaseResult(username, oldUsername);

    Set<UUID> conflicting = new HashSet<>();
    try (MongoCursor<Document> cursor = c.find(new Document("name", username)).iterator()) {
        while (cursor.hasNext()) {
            conflicting.add(getDocumentId(cursor.next()));
        }
    }
    conflicting.remove(uniqueId);

    if (!conflicting.isEmpty()) {
        // remove the mappings for conflicting uuids
        c.deleteMany(Filters.and(conflicting.stream().map(u -> Filters.eq("_id", u)).collect(Collectors.toList())));
        result = result.withOtherUuidsPresent(conflicting);
    }

    return result;
}
 
Example 10
Source File: PersistenceManager.java    From clouditor with Apache License 2.0 5 votes vote down vote up
public void persist(PersistentObject object) {
  try {
    MongoCollection<PersistentObject> coll = this.getCollection(object);

    coll.replaceOne(
        new Document(FIELD_ID, object.getId()), object, new UpdateOptions().upsert(true));
  } catch (MongoException e) {
    LOGGER.error("Error while saving into database: {}", e.getMessage());
  }
}
 
Example 11
Source File: MongoRyaInstanceDetailsRepository.java    From rya with Apache License 2.0 5 votes vote down vote up
@Override
public void update(final RyaDetails oldDetails, final RyaDetails newDetails)
        throws NotInitializedException, ConcurrentUpdateException, RyaDetailsRepositoryException {
    // Preconditions.
    requireNonNull(oldDetails);
    requireNonNull(newDetails);

    if(!newDetails.getRyaInstanceName().equals( instanceName )) {
        throw new RyaDetailsRepositoryException("The instance name that was in the provided 'newDetails' does not match " +
                "the instance name that this repository is connected to. Make sure you're connected to the" +
                "correct Rya instance.");
    }

    if(!isInitialized()) {
        throw new NotInitializedException("Could not update the details for the Rya instanced named '" +
                instanceName + "' because it has not been initialized yet.");
    }

    if(oldDetails.equals(newDetails)) {
        return;
    }

    final MongoCollection<Document> col = db.getCollection(INSTANCE_DETAILS_COLLECTION_NAME);
    final Document oldObj = MongoDetailsAdapter.toDocument(oldDetails);
    final Document newObj = MongoDetailsAdapter.toDocument(newDetails);
    final UpdateResult result = col.replaceOne(oldObj, newObj, new ReplaceOptions());

    //since there is only 1 document, there should only be 1 update.
    if(result.getModifiedCount() != 1) {
        throw new ConcurrentUpdateException("Could not update the details for the Rya instance named '" +
            instanceName + "' because the old value is out of date.");
    }
}
 
Example 12
Source File: RenderDao.java    From render with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Saves the specified tile spec to the database.
 *
 * @param  stackId    stack identifier.
 * @param  tileSpec   specification to be saved.
 *
 * @throws IllegalArgumentException
 *   if any required parameters or transform spec references are missing.
 */
void saveTileSpec(final StackId stackId,
                  final TileSpec tileSpec)
        throws IllegalArgumentException {

    MongoUtil.validateRequiredParameter("stackId", stackId);
    MongoUtil.validateRequiredParameter("tileSpec", tileSpec);
    MongoUtil.validateRequiredParameter("tileSpec.tileId", tileSpec.getTileId());

    final MongoCollection<Document> tileCollection = getTileCollection(stackId);

    final String context = "tile spec with id '" + tileSpec.getTileId();
    validateTransformReferences(context, stackId, tileSpec.getTransforms());

    final Document query = new Document();
    query.put("tileId", tileSpec.getTileId());

    final Document tileSpecObject = Document.parse(tileSpec.toJson());

    final UpdateResult result = tileCollection.replaceOne(query, tileSpecObject, MongoUtil.UPSERT_OPTION);

    LOG.debug("saveTileSpec: {}.{},({}), upsertedId is {}",
              MongoUtil.fullName(tileCollection),
              MongoUtil.action(result),
              query.toJson(),
              result.getUpsertedId());
}
 
Example 13
Source File: MongoOperations.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private static void persistOrUpdate(MongoCollection collection, Object entity) {
    //we transform the entity as a document first
    BsonDocument document = getBsonDocument(collection, entity);

    //then we get its id field and create a new Document with only this one that will be our replace query
    BsonValue id = document.get(ID);
    if (id == null) {
        //insert with autogenerated ID
        collection.insertOne(entity);
    } else {
        //insert with user provided ID or update
        BsonDocument query = new BsonDocument().append(ID, id);
        collection.replaceOne(query, entity, new ReplaceOptions().upsert(true));
    }
}
 
Example 14
Source File: MongoOperations.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private static void update(MongoCollection collection, Object entity) {
    //we transform the entity as a document first
    BsonDocument document = getBsonDocument(collection, entity);

    //then we get its id field and create a new Document with only this one that will be our replace query
    BsonValue id = document.get(ID);
    BsonDocument query = new BsonDocument().append(ID, id);
    collection.replaceOne(query, entity);
}
 
Example 15
Source File: MongodbClientOpsDemo.java    From xian with Apache License 2.0 5 votes vote down vote up
private static void update() {
    MongoCollection<Person> collection = Mongo.getCollection("dianping-collection", Person.class);
    //更新一条document
    collection.updateOne(eq("name", "张三"), combine(set("age", 23), set("name", "Ada Lovelace")));

    // 更新多条document
    UpdateResult updateResult = collection.updateMany(not(eq("zip", null)), set("zip", null));
    System.out.println(updateResult.getModifiedCount());

    // 替换collection(理论上object id是不会被替换的)
    updateResult = collection.replaceOne(eq("name", "张三"), new Person("张三", 20, new Address("香柏广场", "广州", "10086")));
    System.out.println(updateResult.getModifiedCount());
}
 
Example 16
Source File: TwitterCrawler.java    From lumongo with Apache License 2.0 4 votes vote down vote up
public void start() throws TwitterException, IOException {
	Twitter twitter = new TwitterFactory().getInstance();
	twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_KEY_SECRET);
	AccessToken accessToken = new AccessToken(ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
	twitter.setOAuthAccessToken(accessToken);
	
	MongoClient mongo = new MongoClient();
	MongoDatabase db = mongo.getDatabase("twitter");
	final MongoCollection<Document> collection = db.getCollection("sample");
	
	StatusListener listener = new StatusListener() {
		@Override
		public void onStatus(Status status) {
			Document tweet = new Document();
			
			tweet.put("_id", status.getId());
			tweet.put("createdAt", status.getCreatedAt());
			tweet.put("favoriteCount", status.getFavoriteCount());
			tweet.put("retweetCount", status.getRetweetCount());
			if (status.getGeoLocation() != null) {
				tweet.put("lat", status.getGeoLocation().getLatitude());
				tweet.put("long", status.getGeoLocation().getLongitude());
			}
			tweet.put("screenName", status.getUser().getScreenName());
			if (status.getRetweetedStatus() != null) {
				tweet.put("retweetedStatus", status.getRetweetedStatus().getText());
			}
			
			tweet.put("text", status.getText());

			Document query = new Document();
			
			query.put("_id", status.getId());

			collection.replaceOne(query, tweet, new UpdateOptions().upsert(true));
		}
		
		@Override
		public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
		}
		
		@Override
		public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
		}
		
		@Override
		public void onException(Exception ex) {
			ex.printStackTrace();
		}
		
		@Override
		public void onScrubGeo(long userId, long upToStatusId) {
			
		}
		
		@Override
		public void onStallWarning(StallWarning warning) {
			
		}
	};
	
	final TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
	twitterStream.setOAuthConsumer(CONSUMER_KEY, CONSUMER_KEY_SECRET);
	twitterStream.setOAuthAccessToken(accessToken);
	twitterStream.addListener(listener);
	twitterStream.sample();
	
	Runtime.getRuntime().addShutdownHook(new Thread() {
		@Override
		public void run() {
			twitterStream.cleanUp();
		}
	});
	
}
 
Example 17
Source File: UpdateDataForSpecifyingLastReproduction.java    From repairnator with MIT License 4 votes vote down vote up
public static void main(String[] args) {
    String dbConnectionUrl = args[0];
    String dbName = args[1];
    String collectionName = args[2];

    MongoConnection mongoConnection = new MongoConnection(dbConnectionUrl, dbName);
    MongoDatabase database = mongoConnection.getMongoDatabase();
    MongoCollection collection = database.getCollection(collectionName);

    Calendar limitDateMay = Calendar.getInstance();
    limitDateMay.set(2017, Calendar.MAY, 10);

    final List<ObjectId> updatedDocs = new ArrayList<>();

    Set<Integer> ids = new HashSet<>();

    Block<Document> block = new Block<Document>() {

        @Override
        public void apply(Document document) {
            ObjectId documentId = document.getObjectId("_id");

            Object pBuildId = document.get("previousBuildId");

            if (pBuildId instanceof Integer) {
                int previousBuildId = document.getInteger("previousBuildId", -1);
                if (previousBuildId != -1) {
                    boolean lastReproducedBuggyBuild = !ids.contains(previousBuildId);
                    ids.add(previousBuildId);

                    document.append("lastReproducedBuggyBuild", lastReproducedBuggyBuild);
                    collection.replaceOne(eq("_id", documentId), document, new UpdateOptions().upsert( true ));
                    updatedDocs.add(documentId);
                }
            }

        }
    };

    collection.find().sort(orderBy(descending("buildReproductionDate"))).forEach(
            block
    );

    System.out.println("Updated docs: "+updatedDocs.size());

}
 
Example 18
Source File: PutMongo.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    final FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;
    }

    final ComponentLog logger = getLogger();

    final Charset charset = Charset.forName(context.getProperty(CHARACTER_SET).getValue());
    final String mode = context.getProperty(MODE).getValue();
    final String updateMode = context.getProperty(UPDATE_MODE).getValue();
    final WriteConcern writeConcern = getWriteConcern(context);

    try {
        final MongoCollection<Document> collection = getCollection(context, flowFile).withWriteConcern(writeConcern);
        // Read the contents of the FlowFile into a byte array
        final byte[] content = new byte[(int) flowFile.getSize()];
        session.read(flowFile, in -> StreamUtils.fillBuffer(in, content, true));

        // parse
        final Object doc = (mode.equals(MODE_INSERT) || (mode.equals(MODE_UPDATE) && updateMode.equals(UPDATE_WITH_DOC.getValue())))
                ? Document.parse(new String(content, charset)) : JSON.parse(new String(content, charset));

        if (MODE_INSERT.equalsIgnoreCase(mode)) {
            collection.insertOne((Document)doc);
            logger.info("inserted {} into MongoDB", new Object[] { flowFile });
        } else {
            // update
            final boolean upsert = context.getProperty(UPSERT).asBoolean();
            final String updateKey = context.getProperty(UPDATE_QUERY_KEY).evaluateAttributeExpressions(flowFile).getValue();
            final String filterQuery = context.getProperty(UPDATE_QUERY).evaluateAttributeExpressions(flowFile).getValue();
            final Document query;

            if (!StringUtils.isBlank(updateKey)) {
                query = parseUpdateKey(updateKey, (Map)doc);
                removeUpdateKeys(updateKey, (Map)doc);
            } else {
                query = Document.parse(filterQuery);
            }

            if (updateMode.equals(UPDATE_WITH_DOC.getValue())) {
                collection.replaceOne(query, (Document)doc, new UpdateOptions().upsert(upsert));
            } else {
                BasicDBObject update = (BasicDBObject)doc;
                update.remove(updateKey);
                collection.updateOne(query, update, new UpdateOptions().upsert(upsert));
            }
            logger.info("updated {} into MongoDB", new Object[] { flowFile });
        }

        session.getProvenanceReporter().send(flowFile, getURI(context));
        session.transfer(flowFile, REL_SUCCESS);
    } catch (Exception e) {
        logger.error("Failed to insert {} into MongoDB due to {}", new Object[] {flowFile, e}, e);
        session.transfer(flowFile, REL_FAILURE);
        context.yield();
    }
}
 
Example 19
Source File: ClusterHelper.java    From lumongo with Apache License 2.0 4 votes vote down vote up
public void saveClusterConfig(ClusterConfig clusterConfig) throws Exception {

		MongoDatabase db = mongo.getDatabase(database);

		MongoCollection<Document> configCollection = db.getCollection(CLUSTER_CONFIG);

		Document query = new Document();
		query.put(_ID, CLUSTER);

		Document config = new Document();
		config.put(_ID, CLUSTER);
		config.put(DATA, clusterConfig.toDocument());

		configCollection.replaceOne(query, config, new UpdateOptions().upsert(true));

	}
 
Example 20
Source File: ClusterHelper.java    From lumongo with Apache License 2.0 3 votes vote down vote up
public void registerNode(LocalNodeConfig localNodeConfig, String serverAddress) throws Exception {

		MongoDatabase db = mongo.getDatabase(database);

		MongoCollection<Document> membershipCollection = db.getCollection(CLUSTER_MEMBERSHIP);

		Document index = new Document();
		index.put(SERVER_ADDRESS, 1);
		index.put(INSTANCE, 1);

		System.out.println(localNodeConfig.getHazelcastPort());

		IndexOptions options = new IndexOptions().unique(true);
		membershipCollection.createIndex(index, options);

		Document search = new Document();
		search.put(SERVER_ADDRESS, serverAddress);
		search.put(INSTANCE, localNodeConfig.getHazelcastPort());

		Document object = new Document();
		object.put(SERVER_ADDRESS, serverAddress);
		object.put(INSTANCE, localNodeConfig.getHazelcastPort());
		object.put(DATA, localNodeConfig.toDocument());

		membershipCollection.replaceOne(search, object, new UpdateOptions().upsert(true));

	}