Guido Anselmi
Guido Anselmi

Reputation: 3922

How to Update a Document in MongoDB w/Java Driver

I am trying to update a document using as criteria the Mongo ObjectId which I store in a parallel field contentGroupId but it is not working.

What is the best practice for updating a document in Mongo using the Java Driver when you are using the internal id as the primary key?

@Override
public void updateContentGroup( ContentGroup contentGroup ) {    

    DBCollection contentGroupCollection = db.getCollection( "contentGroups" );

    Gson gson = new Gson();
    String json = gson.toJson( contentGroup );

    DBObject contentGroupDoc = (DBObject) JSON.parse( json );        

    BasicDBObject criteriaObject = new BasicDBObject();
    criteriaObject.append( "_id", "ObjectId(\"520a56b730047339c26ec1fa\")");

    contentGroupCollection.update( criteriaObject, contentGroupDoc );
}

Thanks-in-advance,

Guido

Upvotes: 0

Views: 209

Answers (1)

Ori Dar
Ori Dar

Reputation: 19020

I think your problem is here:

criteriaObject.append( "_id", "ObjectId(\"520a56b730047339c26ec1fa\")");

Should be:

criteriaObject.append( "_id", new ObjectId("520a56b730047339c26ec1fa");

That way the field value is treated as an object id, not as string (containing the literal "ObjectId")

Upvotes: 1

Related Questions