Search code examples
javamongodbmongodb-querycrud

Update document in MongoDB with Java


I'm using MongoDB 3.2 and MongoDB Java Driver 3.2. I want to update the value the document having its ID. In order to do that I tried to use the following two approaches (found in Stackoverflow and MongoDB Blog):

Approach #1:

for(String docID : expiredDocsIDs) {

    Bson filter = Filters.eq("_id", docID);

    Bson updates = Updates.set("isExpired", true);

    dbCollection.findOneAndUpdate(filter, updates);
}

Approach #2:

expiredDocsIDs.stream()
    .forEach(docID -> {

        BasicDBObject updateFields = new BasicDBObject();
        updateFields.append("isExpired", true);
        updateFields.append("fetchStatus", "FETCHED");

        BasicDBObject setQuery = new BasicDBObject();
        setQuery.append("$set", updateFields);

        BasicDBObject searchQuery = new BasicDBObject("_id", docID);

        dbCollection.updateOne(searchQuery, setQuery);
});

None of these approaches does not work. It iterates over the list of documents IDs, executes the code but at the end of the code, when I check the documents in DB there is no any change in the documents' field I tried to update.

How can I update the specific document in MongoDB?


Solution

  • As BlakesSeven correctly noted, the problem was with a casting of _id field. The original code sent this parameter as String while the correct way is to send a parameter of ObjectId type.

    The correct and worked code form MongoDB 3.2:

    this.trackedEpisodesReg.entrySet().stream()
        .filter(ep -> ep.getValue().isExpired())
        .forEach(ep -> {
    
            BasicDBObject updateFields = new BasicDBObject();
            updateFields.append("isExpired", true);
    
            BasicDBObject setQuery = new BasicDBObject();
            setQuery.append("$set", updateFields);
    
            BasicDBObject searchQuery = new BasicDBObject("_id", new ObjectId(ep.getValue().getEpisodeID()));
    
            dbCollection.updateOne(searchQuery, setQuery);
        });