MongoDB从嵌入文档数组中删除项目

时间:2017-09-18 12:13:42

标签: php mongodb

我有以下数据结构:

{ 
_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更新运算符,但它没有从嵌入/嵌入文档的数组中提取元素的示例,我无法弄清楚:

我想提取网站 ='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]);

更新 我同意这是一个重复的问题和答案。我只能找到以下内容:

MongoDB $pull array 2 level

因此该命令确实拉低级别元素,但仅从时间点0开始:

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

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

0 个答案:

没有答案