I'm trying to delete an object from datastore but it's not deleting it. Code is given below:
MoIADocument moIADoc = new MoIADocument();
// update fields in moIADoc object
ds.save(moIADoc);
printDBDocs();
// create a query to retrieve objects
QueryResults<MoIADocument> foundResults = dao.find(query);
List<MoIADocument> list = foundResults.asList();
for (MoIADocument obj : list) {
ds.delete(obj);
MoDBIATopic topicBO = obj.getData().get(EnumChannelType.FACEBOOK).getData().get(GraphConstants.Topic_Default);
topicBO.setInfluence(topicBO.getInfluence() * 25);
ds.save(obj);
}
printDBDocs();
###########################
the result of first print (in JSON format) is:
###########################
obj in for
loop is:
###########################
and after for loop the print statement gives two objects as:
Why is it not deleting old object by mongoConstants.ds.delete(obj);
? And I have annotated id
field ad @Id
but still two objects are saved with same id
. How is this possible? How can we force to overwrite an object if id
is same?
@Id
@Indexed
private String id;
Note: id
is the top level id
as indicated in JSON.
And I tried using query as:
Query<MoIADocument> query1 = ds.createQuery(MoIADocument.class).disableValidation();
query1.field("id").equal(obj.getId());
ds.delete(query1);
This too not working as expected.
EDIT:
Problem looks like in query result. Using above query1
, it returned zero results.
Problem was using a String id
as @Id
field. Actually it should be ObjectId id
. WIth this change class become as below:
@Entity("Collection_IAGlobals")
public class MoDBIADocument {
@Id
@Indexed
private ObjectId id;
// some more fields
}
and updating as:
QueryResults<MoIADocument> foundResults = dao.find(query);
List<MoIADocument> list = foundResults.asList();
for (MoIADocument obj : list) {
//do modifications in obj
dao.save(obj);
}
this way there is no need to delete
old object. It replaces old object with new one (since they are having same id
).
Works fine using both ds
and dao
.
But now, new problem with setting id
field. If I set using some string as:
moIADoc.setId(new ObjectId("123456"));
it is resulting into following error:
Exception in thread "main" java.lang.IllegalArgumentException: invalid ObjectId [123456]
at org.bson.types.ObjectId.<init>(ObjectId.java:128)
at org.bson.types.ObjectId.<init>(ObjectId.java:122)
It works fine any of other methods, like:
// don't set id field
//OR
//set using default constructor of ObjectId
moIADoc.setId(new ObjectId());
//OR use other constructors e.g.
moIADoc.setId(new ObjectId(new Date(), 123456));
So, the question is why ObjectId
is not taking String
argument?