Java insert value to Array in MongoDB Java insert value to Array in MongoDB json json

Java insert value to Array in MongoDB


My goodness! This question got me descending into the long forgotten world of Java again - after all these years... ;) Anyhoo, here's a complete working example that might give you a clue of what's going on. You can run the code several times and see how the number of elements in the "Subscribed Topics" array increases.

I used the following driver: https://oss.sonatype.org/content/repositories/releases/org/mongodb/mongo-java-driver/3.3.0/mongo-java-driver-3.3.0.jar

import com.mongodb.MongoClient;import com.mongodb.client.MongoDatabase;import com.mongodb.client.MongoCollection;import org.bson.Document;import org.bson.conversions.Bson;import static com.mongodb.client.model.Filters.*;import static com.mongodb.client.model.Updates.*;public class MongoDbPush {  public static void main(String[] args)  {    MongoClient mongoClient = new MongoClient();    MongoDatabase database = mongoClient.getDatabase("pushExampleDb");    MongoCollection<Document> collection = database.getCollection("pushExampleCollection");    String sensorType = "Temperature";    // try to load existing document from MongoDB    Document document = collection.find(eq("Sensor Type", sensorType)).first();    if(document == null)    {      // no test document, let's create one!      document = new Document("Sensor Type", sensorType);      // insert it into MongoDB      collection.insertOne(document);      // read it back from MongoDB      document = collection.find(eq("Sensor Type", sensorType)).first();    }    // see what it looks like in JSON (on the first run you will notice that it has got an "_id" but no "Subscribed Topics" array yet)    System.out.println(document.toJson());    // update the document by adding an entry to the "Subscribed Topics" array    Bson filter = eq("Sensor Type", sensorType);    Bson change = push("Subscribed Topics", "Some Topic");    collection.updateOne(filter, change);    // read one more time from MongoDB    document = collection.find(eq("Sensor Type", sensorType)).first();    // see what the document looks like in JSON (on the first run you will notice that the "Subscribed Topics" array has been created and has got one element in it)    System.out.println(document.toJson());    mongoClient.close();  }}


The above method still works, however, with updated Mongo Driver the below is also a viable mechanism.

The below works for Mongo Driver 3.6 onward (in this case using 3.12.4)

MongoClient mongoClient = new MongoClient();MongoDatabase database = mongoClient.getDatabase("pushExampleDb");MongoCollection<Document> collection = database.getCollection("pushExampleCollection");collection.findOneAndUpdate(Filters.eq("Sensor Type",<theSensorTypeNameComesHere>),                             Updates.pushEach("Subscribed Topics",<listContainingTheValuesComeHere>));

Refer: $push and $each from MongoDB Manual