Mongo - 根据用户名从一个集合中的多个数组中删除多个元素

Mongo - Delete multiple elements from multiple arrays in one collection based off a username

我收集了一组诈骗 phone 号码,其中包含来自不同用户的评论。每个用户都有一个唯一的显示名称。我正在尝试删除特定于该用户名的所有评论。到目前为止,我可以使用以下方法找到包含来自该特定用户名的评论的文档:

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

我只想删除用户对所有帖子的评论,而不是帖子本身。我觉得我很接近但找不到

查找结果:

{ "_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 }

您可以使用更新运算符 $pull 删除与特定查询匹配的数组元素。你的情况:

db.collection.updateMany(
    {"comments":{$elemMatch:{creator:"name"}}}, // original query
    {
      $pull: {
        comments: {
          creator: "name"
        }
      }
    })