mongodb从多个文档中删除特定的数组项(nodejs)

时间:2019-05-17 08:45:21

标签: javascript node.js mongodb mongodb-query

我正在尝试从多个文档中删除特定的数组项。假设我们有以下文档:

{
  _id: ...,
  email: 'person1@email.com',
  tasks: [
     { title: 'some titleA', uuid: 'uuidA'},
     { title: 'some titleB', uuid: 'uuidB'},
     { title: 'some titleC', uuid: 'uuidC'},
  ]
},
{
  _id: ...,
  email: 'person2@email.com',
  tasks: [
     { title: 'some titleA', uuid: 'uuidA'},
     { title: 'some titleB', uuid: 'uuidB'},
     { title: 'some titleC', uuid: 'uuidC'},
  ]
},
{
  _id: ...,
  email: 'person3@email.com',
  tasks: [
     { title: 'some titleA', uuid: 'uuidA'},
     { title: 'some titleB', uuid: 'uuidB'},
     { title: 'some titleC', uuid: 'uuidC'},
  ]
}

然后,在给定电子邮件列表的情况下,说person1@email.comperson2@email.comtasks匹配那些电子邮件的任何文档数组中删除,其中uuid值为{ {1}}。

结果应该是

uuidB

这是我到目前为止尝试过的:

{
  _id: ...,
  email: 'person1@email.com',
  tasks: [
     { title: 'some titleA', uuid: 'uuidA'},
     { title: 'some titleC', uuid: 'uuidC'},
  ]
},
{
  _id: ...,
  email: 'person2@email.com',
  tasks: [
     { title: 'some titleA', uuid: 'uuidA'},
     { title: 'some titleC', uuid: 'uuidC'},
  ]
},
{
  _id: ...,
  email: 'person3@email.com',
  tasks: [
     { title: 'some titleA', uuid: 'uuidA'},
     { title: 'some titleB', uuid: 'uuidB'},
     { title: 'some titleC', uuid: 'uuidC'},
  ]
}

谢谢您的帮助!

1 个答案:

答案 0 :(得分:1)

$elemMatchqueryprojection运算符,而不是update operator。因此,您不能在这里使用它。

您需要使用“绝对”对象结构

model.updateMany(
  { "email": { "$in": emails }},
  { "$pull": { "tasks": { "uuid": uuid }}}
)