Skip to content

Instantly share code, notes, and snippets.

@abyrd
Last active September 5, 2017 16:43
Show Gist options
  • Save abyrd/a674b3388acb8d48f6b650e1efd032ed to your computer and use it in GitHub Desktop.
Save abyrd/a674b3388acb8d48f6b650e1efd032ed to your computer and use it in GitHub Desktop.
package com.conveyal.datatools.manager.persistence;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.codecs.pojo.PojoCodecProvider;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Updates.set;
import static org.bson.codecs.configuration.CodecRegistries.fromProviders;
import static org.bson.codecs.configuration.CodecRegistries.fromRegistries;
/**
* Demonstrate updating a single field of a document in Mongo.
* This can be done with JSON or with Java objects.
*/
public class MongoUpdateNested {
public static final Logger LOG = LoggerFactory.getLogger(MongoUpdateNested.class);
public ObjectId id = new ObjectId();
public Nest1 inside;
public static void main (String[] args) {
PojoCodecProvider pojoCodecProvider = PojoCodecProvider.builder().automatic(true).build();
CodecRegistry pojoCodecRegistry = fromRegistries(MongoClient.getDefaultCodecRegistry(),
fromProviders(pojoCodecProvider));
MongoClient mongoClient = new MongoClient("localhost",
MongoClientOptions.builder().codecRegistry(pojoCodecRegistry).build());
MongoDatabase mongoDatabase = mongoClient.getDatabase("nest_test");
MongoCollection<MongoUpdateNested> collection = mongoDatabase.getCollection(MongoUpdateNested.class.getSimpleName(), MongoUpdateNested.class);
MongoUpdateNested nest0 = new MongoUpdateNested();
collection.insertOne(nest0);
// Update the top level object, giving it a nested object from a JSON document (which could be parsed from text)
Document subDocument = new Document("content", 12345)
.append("more", "a")
.append("blah", "b");
collection.updateOne(eq(nest0.id), set("inside", subDocument));
MongoUpdateNested nest0Deserialized = collection.find(eq(nest0.id)).first();
LOG.info("content: {}", nest0Deserialized.inside.content);
// Now update the nested field using a Java object rather than a JSON document.
Nest1 nest1 = new Nest1();
nest1.content = 9999;
collection.updateOne(eq(nest0.id), set("inside", nest1));
nest0Deserialized = collection.find(eq(nest0.id)).first();
LOG.info("content: {}", nest0Deserialized.inside.content);
}
public static class Nest1 {
public int content = 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment