use of com.mongodb.client.result.UpdateResult in project morphia by mongodb.
the class TestUpdateOperations method testUpdateRef.
@Test
public void testUpdateRef() {
final ContainsPic cp = new ContainsPic();
cp.setName("cp one");
getDs().save(cp);
final Pic pic = new Pic();
pic.setName("fist");
getDs().save(pic);
Query<ContainsPic> query = getDs().find(ContainsPic.class).filter(eq("name", cp.getName()));
UpdateResult result = query.update(set("pic", pic)).execute();
Assert.assertEquals(result.getModifiedCount(), 1);
// test reading the object.
final ContainsPic cp2 = getDs().find(ContainsPic.class).iterator(new FindOptions().limit(1)).next();
assertThat(cp2, is(notNullValue()));
MatcherAssert.assertThat(cp.getName(), CoreMatchers.is(cp2.getName()));
MatcherAssert.assertThat(cp2.getPic(), is(notNullValue()));
MatcherAssert.assertThat(cp2.getPic().getName(), is(notNullValue()));
MatcherAssert.assertThat(pic.getName(), CoreMatchers.is(cp2.getPic().getName()));
// test reading the object.
final ContainsPic cp3 = getDs().find(ContainsPic.class).iterator(new FindOptions().limit(1)).next();
assertThat(cp3, is(notNullValue()));
MatcherAssert.assertThat(cp.getName(), CoreMatchers.is(cp3.getName()));
MatcherAssert.assertThat(cp3.getPic(), is(notNullValue()));
MatcherAssert.assertThat(cp3.getPic().getName(), is(notNullValue()));
MatcherAssert.assertThat(pic.getName(), CoreMatchers.is(cp3.getPic().getName()));
}
use of com.mongodb.client.result.UpdateResult in project morphia by mongodb.
the class TestDatastore method testRefresh.
@Test
public void testRefresh() {
FacebookUser steve = getDs().save(new FacebookUser(1, "Steve"));
assertEquals(steve.loginCount, 0);
UpdateResult loginCount = getDs().find(FacebookUser.class).update(inc("loginCount", 10)).execute();
assertEquals(loginCount.getModifiedCount(), 1);
getDs().refresh(steve);
assertEquals(steve.loginCount, 10);
loginCount = getDs().find(FacebookUser.class).update(set("username", "Mark"), set("loginCount", 1)).execute();
assertEquals(loginCount.getModifiedCount(), 1);
getDs().refresh(steve);
assertEquals(steve.loginCount, 1);
assertEquals(steve.username, "Mark");
}
use of com.mongodb.client.result.UpdateResult in project morphia by mongodb.
the class TestDatastore method testUpdateWithCollation.
@Test
public void testUpdateWithCollation() {
getDs().save(asList(new FacebookUser(1, "John Doe"), new FacebookUser(2, "john doe")));
final Update<FacebookUser> update = getDs().find(FacebookUser.class).filter(eq("username", "john doe")).update(inc("loginCount"));
UpdateResult results = update.execute();
assertEquals(results.getModifiedCount(), 1);
assertEquals(getDs().find(FacebookUser.class).filter(eq("id", 1)).iterator(new FindOptions().limit(1)).next().loginCount, 0);
assertEquals(getDs().find(FacebookUser.class).filter(eq("id", 2)).iterator(new FindOptions().limit(1)).next().loginCount, 1);
results = update.execute(new UpdateOptions().multi(true).collation(Collation.builder().locale("en").collationStrength(SECONDARY).build()));
assertEquals(results.getModifiedCount(), 2);
assertEquals(getDs().find(FacebookUser.class).filter(eq("id", 1)).iterator(new FindOptions().limit(1)).next().loginCount, 1);
assertEquals(getDs().find(FacebookUser.class).filter(eq("id", 2)).iterator(new FindOptions().limit(1)).next().loginCount, 2);
}
use of com.mongodb.client.result.UpdateResult in project graylog2-server by Graylog2.
the class V20170110150100_FixAlertConditionsMigration method upgrade.
@Override
@SuppressWarnings("unchecked")
public void upgrade() {
if (clusterConfigService.get(MigrationCompleted.class) != null) {
LOG.debug("Migration already done.");
return;
}
final ImmutableSet.Builder<String> modifiedStreams = ImmutableSet.builder();
final ImmutableSet.Builder<String> modifiedAlertConditions = ImmutableSet.builder();
for (Document document : collection.find().sort(ascending(FIELD_CREATED_AT))) {
final String streamId = document.getObjectId(FIELD_ID).toHexString();
if (!document.containsKey(FIELD_ALERT_CONDITIONS)) {
continue;
}
final List<Document> alertConditions = (List<Document>) document.get(FIELD_ALERT_CONDITIONS);
// Need to check if the following fields are integers:
//
// FieldContentValue: grace, backlog
// FieldValue: grace, backlog, time, threshold
// MessageCount: grace, backlog, time, threshold
final Set<String> intFields = ImmutableSet.of("grace", "backlog", "time", "threshold");
for (Document alertCondition : alertConditions) {
final String alertConditionId = alertCondition.get("id", String.class);
final String alertConditionTitle = alertCondition.get("title", String.class);
final Document parameters = alertCondition.get("parameters", Document.class);
for (String field : intFields) {
final Object fieldValue = parameters.get(field);
// No need to convert anything if the field does not exist or is already an integer
if (fieldValue == null || fieldValue instanceof Integer) {
continue;
}
if (!(fieldValue instanceof String)) {
LOG.warn("Field <{}> in alert condition <{}> ({}) of stream <{}> is not a string but a <{}>, not trying to convert it!", field, alertConditionId, alertConditionTitle, streamId, fieldValue.getClass().getCanonicalName());
continue;
}
final String stringValue = parameters.get(field, String.class);
final Integer intValue = Ints.tryParse(stringValue);
LOG.info("Converting value for field <{}> from string to integer in alert condition <{}> ({}) of stream <{}>", field, alertConditionId, alertConditionTitle, streamId);
if (intValue == null) {
LOG.error("Unable to parse \"{}\" into integer!", fieldValue);
}
final UpdateResult result = collection.updateOne(eq(FIELD_ALERT_CONDITIONS_ID, alertConditionId), set(ALERT_CONDITIONS_PARAMETERS_PREFIX + field, intValue));
// Use UpdateResult#getMatchedCount() instead of #getModifiedCount() to make it work on MongoDB 2.4
if (result.getMatchedCount() > 0) {
modifiedStreams.add(streamId);
modifiedAlertConditions.add(alertConditionId);
} else {
LOG.warn("No document modified for alert condition <{}> ({})", alertConditionId, alertConditionTitle);
}
}
}
}
clusterConfigService.write(MigrationCompleted.create(modifiedStreams.build(), modifiedAlertConditions.build()));
}
use of com.mongodb.client.result.UpdateResult in project mongo-java-driver by mongodb.
the class PojoQuickTour method main.
/**
* Run this main method to see the output of this quick example.
*
* @param args takes an optional single argument for the connection string
*/
public static void main(final String[] args) {
MongoClient mongoClient;
if (args.length == 0) {
// connect to the local database server
mongoClient = MongoClients.create();
} else {
mongoClient = MongoClients.create(args[0]);
}
// create codec registry for POJOs
CodecRegistry pojoCodecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(), fromProviders(PojoCodecProvider.builder().automatic(true).build()));
// get handle to "mydb" database
MongoDatabase database = mongoClient.getDatabase("mydb").withCodecRegistry(pojoCodecRegistry);
// get a handle to the "people" collection
MongoCollection<Person> collection = database.getCollection("people", Person.class);
// drop all the data in it
collection.drop();
// make a document and insert it
Person ada = new Person("Ada Byron", 20, new Address("St James Square", "London", "W1"));
System.out.println("Original Person Model: " + ada);
collection.insertOne(ada);
// Person will now have an ObjectId
System.out.println("Mutated Person Model: " + ada);
// get it (since it's the only one in there since we dropped the rest earlier on)
Person somebody = collection.find().first();
System.out.println(somebody);
// now, lets add some more people so we can explore queries and cursors
List<Person> people = asList(new Person("Charles Babbage", 45, new Address("5 Devonshire Street", "London", "W11")), new Person("Alan Turing", 28, new Address("Bletchley Hall", "Bletchley Park", "MK12")), new Person("Timothy Berners-Lee", 61, new Address("Colehill", "Wimborne", null)));
collection.insertMany(people);
System.out.println("total # of people " + collection.countDocuments());
System.out.println("");
// lets get all the documents in the collection and print them out
Consumer<Person> printBlock = new Consumer<Person>() {
@Override
public void accept(final Person person) {
System.out.println(person);
}
};
collection.find().forEach(printBlock);
System.out.println("");
// now use a query to get 1 document out
somebody = collection.find(eq("address.city", "Wimborne")).first();
System.out.println(somebody);
System.out.println("");
// now lets find every over 30
collection.find(gt("age", 30)).forEach(printBlock);
System.out.println("");
// Update One
collection.updateOne(eq("name", "Ada Byron"), combine(set("age", 23), set("name", "Ada Lovelace")));
System.out.println("");
// Update Many
UpdateResult updateResult = collection.updateMany(not(eq("zip", null)), set("zip", null));
System.out.println(updateResult.getModifiedCount());
System.out.println("");
// Replace One
updateResult = collection.replaceOne(eq("name", "Ada Lovelace"), ada);
System.out.println(updateResult.getModifiedCount());
// Delete One
collection.deleteOne(eq("address.city", "Wimborne"));
// Delete Many
DeleteResult deleteResult = collection.deleteMany(eq("address.city", "London"));
System.out.println(deleteResult.getDeletedCount());
// Clean up
database.drop();
// release resources
mongoClient.close();
}
Aggregations