这个问题在这里已有答案:

我有以下数据结构:

{ 
_id: 599cfc236ed0d81c98007f66
site: 'abc'
timepoints [
    { timepoint: 0
      testSites: [{testSite: 'abc', address: '123'},
                  {testSite: 'mno', address: '789'}],
    },
    { timepoint: 2
      testSites: [{testSite: 'abc', address: '123'}],
    },
    { timepoint: 4
      testSites: [{testSite: 'mno', address: '789'}],
    },
  ]
}

我已经阅读了$pull的MongoDB更新运算符,但它没有从嵌入/嵌入文档的数组中提取元素的示例,我无法弄清楚:

我想拉出 site = 'abc'和 testSite = 'abc'的所有元素,结果将是:

{ 
_id: 599cfc236ed0d81c98007f66
site: 'abc'
timepoints [
    { timepoint: 0
      testSites: [{testSite: 'mno', address: '789'}],
    },
    { timepoint: 2
      testSites: [],
    },
    { timepoint: 4
      testSites: [{testSite: 'mno', address: '789'}],
    },
  ]
}

我尝试了以下命令,但它提取了所有时间点文档,而不是testSites中的嵌入文档:

$db->collection1->update(
         ['site' => 'abc'],
         ['$pull' => ['timepoints' => ['testSites' => ['$elemMatch' => ['testSite' => 'abc']]]]],
         ['multi' => true]);

UPDATE: 我同意这是一个带有答案的重复问题 . 我只能找到以下内容:

MongoDB $pull array 2 level

所以命令确实拉低级元素,但只从时间点0开始:

db.collection1.update({'site': 'abc', 
                       'timepoints.testSites.testSite': 'abc'},
                      {'$pull': {'timepoints.$.testSites': {'testSite': 'abc'}}},
                      {'multi': true}
                     );

为什么时间点2中的第二次出现没有被拉出?