J.Olufsen
J.Olufsen

Reputation: 13915

How to update specific filed in mongodb document using Spring?

I need to search product document by ObjectId and update specific field listed using Spring data framework. I get error from IDE when I try to use update method on injected MongoOperations

@Repository
public class ProductDao  {
@Autowired
    private MongoOperations mongoOperations;

public void cancel(Long id) {
        mongoOperations.update("{"_id":"00000000001"}","$set{"listed":"False"}"); // error // something like that
    }
}

I think I need to use DBCollection but I have issues setting it up. To update field I need to use $set

How to make it working?

Upvotes: 0

Views: 1715

Answers (1)

dectarin
dectarin

Reputation: 1006

I don't have the ability to test this at the moment but this is the way you should go about it. I am assuming that your product documents are mapped in a Product.class in the snippet below

mongoOperations.updateFirst(new Query(where("_id").is("00000000001")),Update.update("listed", "False"), Product.class)

If you wanted to update many documents that match the query you should use the updateMulti function instead.

Also, the two imports you need are :

import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

Upvotes: 3

Related Questions