一次删除不同文档中多次出现的嵌入数组元素

时间:2018-06-11 11:17:48

标签: mongodb

/* 1 */
{
    "_id" : ObjectId("5b17aa58240d110001387ddd"),
    "user_id" : ObjectId("5896baf66b95266c0686a917"),
    "name" : "My Collection",
    "lower_case_name" : "my collection",
    "problem_ids" : [ 
        ObjectId("5b17a952240d110001f2a0fc")
    ],
    "created_at" : ISODate("2018-06-06T09:33:12.734Z"),
    "modified_at" : ISODate("2018-06-11T11:09:47.805Z")
}

/* 2 */
{
    "_id" : ObjectId("5b1e4f9b240d110001444432"),
    "user_id" : ObjectId("5896baf66b95266c0686a917"),
    "name" : "Halla",
    "lower_case_name" : "halla",
    "problem_ids" : [ 
        ObjectId("5b17a952240d110001f2a0fc")
    ],
    "created_at" : ISODate("2018-06-11T10:31:55.924Z"),
    "modified_at" : ISODate("2018-06-11T11:09:45.406Z")
}

我想在当前正在执行的单个查询中删除problem_ids ObjectId("5b17a952240d110001f2a0fc")

db.collections.update({"user_id": ObjectId("5896baf66b95266c0686a917")}, {$pull: {problem_ids: ObjectId("5b17a952240d110001f2a0fc")}})

但它只从第一个文件中删除

1 个答案:

答案 0 :(得分:0)

  

使用{multi:true}更新多个文档

 db.collections.update(
    {"user_id": ObjectId("5896baf66b95266c0686a917")}, 
    {$pull: {problem_ids: ObjectId("5b17a952240d110001f2a0fc")}},
    {multi: true}
  );