Java insert value to Array in MongoDB

Viewed 3306

im new to MongoDB and completely confused by the queries. I simply need to update a document in a mongodb database by adding a string value (example: Temperature) to a list of strings. From research I know that I have to use the $push method for that. I think the code has to look somehow like this:

BasicDBObject newDocument = new BasicDBObject().append("$set", 
new BasicDBObject().append("Subscribed Topics", topic));

collection.update(new BasicDBObject().append("Sensor Type", sensorType), newDocument);
new BasicDBObject("$push",
new BasicDBObject("Subscribed Topics", topic));

The field with the array is called "Subscribed Topics", "topic" is a String (Temperature). Then I want to update the document in the collection with the corresponding "Sensor Type". However, I do not really know how to call the $push part correctly. I hope someone can help me sort this part of the code.

Best regards.

Update, I tried to implemented as suggested in the duplicate question but still got error. Very unsure if thats the right way anyway.

 DBObject listItem = new BasicDBObject("Subscribed Topics", "Light");
             DBObject updateQuery = new BasicDBObject("$push", listItem);
             collection.update(query, updateQuery);`

I create a new Object with the value Light in for Key Subscribed Topics (the array). Why do I push it to a new Object then?

2 Answers

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

Related