1

How can I remove the objects from a mongo collection, by passing a list of objects to remove: I am using spring and mongo repository, below is my code:

 public void removeDocuments(List<PayloadLogs> listLogs){

     String collectionName = mongoTemplate.getCollectionName(Logs.class);
     Query removeQuery = Query.query(Criteria.where("typeHash").in(listLogs));

// this does not removes the documents.
    this.mongoTemplate.findAllAndRemove(removeQuery, PayloadLogs.class, collectionName);
}

Query log:

db.getCollection('payloadLogs').find({
"creativeHash": {
    "$in": [{
        "creativeHash": "21540209fa87504bbbb0dd173c41d742",
        "lastAccessedAt": null,
        ....
    }]
}

});

4
  • 2
    You actually don't want to pass in the whole object. You just need a "unique identifier" or at least something that identifies the documents to remove from the collection. Either a single value or a list of values that matches the whole thing. In this case you just extract the "creativeHash" values as a list of those values only. Provided that does identify the documents to remove and it would not match other documents of course. Commented Aug 22, 2017 at 8:02
  • Thank you @NeilLunn, lets say I have a list of objects fetch on some complex criteria already written. How can I remove these ? Or I need to create a new list with "logHash" only ? duplicating the records. Commented Aug 22, 2017 at 8:23
  • 1
    If you need a "list" with more than a single field value as criteria then you would use $or instead. Since $in is essentially "shorthand" for $or on a single property, then that is the logical course. You should spend some time reading Query and Projection Operators and understanding where each is actually applied. Once you understand how each is actually applied, it answers a lot of questions. Commented Aug 22, 2017 at 8:29
  • @NeilLunn: If you can post your comment as Answer I will Accept it. Thanks. Commented Aug 22, 2017 at 9:01

1 Answer 1

1

I think this will be helpful, add your ids to list and will remove by ids

  BasicDBObject query = new BasicDBObject();
  List<Integer> list = new ArrayList<Integer>();
  list.add(10004);
  list.add(10005);
  query.put("_id", new BasicDBObject("$in", list));
  collection.remove(query);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.