0

I have a collection of scam phone numbers containing comments from different users. Each user has a unique display name. I am trying to delete all comments specific to that user name. So far I can find the documents containing comments from that specific username using:

db.collection.find({"comments":{$elemMatch:{creator:"name"}}})

I want to delete only the user's comments of all posts, not the posting itself. I feel like I'm close but can't find a

Find results:

{ "_id" : ObjectId("5b84a319ec18e50d9093f3aa"), 
"phoneNumber" : 2334445555, 
"flags" : 1, 
"description" : "Charity", 
"comments" : [ 
{ "_id" : ObjectId("5b84a319ec18e50d9093f3ab"), "content" : "Red cross asked me to donate using Moneygram", "creator" : "jv3123", "created" : ISODate("2018-08-28T01:19:21.368Z") } ], "created" : ISODate("2018-08-28T01:19:21.369Z"), "__v" : 0 }


{ "_id" : ObjectId("5b84a4e2ec18e50d9093f3ac"), 
"phoneNumber" : 2334445555, 
"flags" : 1, 
"description" : "Charity", 
"comments" : [ 
{ "_id" : ObjectId("5b84a4e2ec18e50d9093f3ad"), "content" : "Red cross rep asked me to send money through Moneygram", "creator" : "jv3123", "created" : ISODate("2018-08-28T01:26:58.532Z") } ], "db.phoneNumberData.find({"comments":{$elemMatch:{creator:"jv3123"}}})

{ "_id" : ObjectId("5b84a319ec18e50d9093f3aa"), 
"phoneNumber" : 2334445555, 
"flags" : 1, 
"description" : "Charity", 
"comments" : [ { "_id" : ObjectId("5b84a319ec18e50d9093f3ab"), "content" : "Red cross asked me to donate using Moneygram", "creator" : "jv3123", "created" : ISODate("2018-08-28T01:19:21.368Z") } ], "created" : ISODate("2018-08-28T01:19:21.369Z"), "__v" : 0 }

{ "_id" : ObjectId("5b84a4e2ec18e50d9093f3ac"), 
"phoneNumber" : 2334445555, "flags" : 1, "description" : "Charity", "comments" : [ { "_id" : ObjectId("5b84a4e2ec18e50d9093f3ad"), "content" : "Red cross rep asked me to send money through Moneygram", "creator" : "jv3123", "created" : ISODate("2018-08-28T01:26:58.532Z") } ], "created" : ISODate("2018-08-28T01:26:58.532Z"), "__v" : 0 }
kmdreko
  • 42,554
  • 6
  • 57
  • 106
Vega
  • 11
  • 3

1 Answers1

3

You can use the update operator $pull to remove array elements matching a specific query. In your case:

db.collection.updateMany(
    {"comments":{$elemMatch:{creator:"name"}}}, // original query
    {
      $pull: {
        comments: {
          creator: "name"
        }
      }
    })
kmdreko
  • 42,554
  • 6
  • 57
  • 106
  • Is there a way to use `$pull` with `$slice` so as to remove a *range* of items from an array? eg 'pull items from the array with indexes 0 - 2' would remove 3 items. – user1063287 Jul 26 '20 at 08:09
  • 1
    @user1063287 you can with MongoDB 4.2 update pipeline using `$set` and `$slice` as seen in [this answer](https://stackoverflow.com/a/62551740) – kmdreko Jul 26 '20 at 18:29