如何查找字段值为null或为空的所有文档

时间:2016-04-15 10:38:38

标签: php mongodb mongodb-query

我正在尝试编写一个简单的Mongo查询来返回字段值为null的所有文档(或者是一个空数组,我不确定你称之为什么)。

这是我的查询;

db.getCollection('contact').find({'poco.name.email':false})

以下是使用RoboMongo的我的收藏的截图;

screenshot of my collection using RoboMongo

最终,我需要将其转移到某些PHP。到目前为止,我有这个工作;

$conditions = array_merge($conditions, [
  'owner.$id' => $this->getId(),
  'poco.name.familyName' => "Smith",
  //not sure what goes here.. something like
  //'poco.emails' => null,
]);

return Model_Mongo_Contact::getContacts($conditions, $sort, $fields, $limit, $skip); 

如果没有更多的方法访问方法,那可能会更难回答。或许不是我对Mongo来说很新,这可能是非常明显的。

2 个答案:

答案 0 :(得分:0)

我不是PHP专家,但我会在mongo shell中做:

db.collection.find({
  $and: [
    {"poco.email":{$exists: true}}, 
    {"poco.email":{$ne: []}}
  ]})

上面的查询将列出poco.name.email未丢失且不为空的所有文档。

答案 1 :(得分:0)

寻找"空"时的基本概念数组甚至"不存在"是使用"点符号"的属性并搜索数组的0索引不存在的位置。这可以通过使用$exists运算符来实现:

$conditions = array_merge($conditions, [
  'owner.$id' => $this->getId(),
  'poco.name.familyName' => "Smith",
  'poco.emails.0' => array( '$exists' => FALSE )
]);

如果根本没有属性,或者它不是数组(因此没有"0"字段属性)或者确实是"空"数组(因为第一个索引没有内容)。

当字段实际上是"索引"时,这最有效。所以如果在你的正常情况下#34;您拥有的结构"子文件"在数组元素内部,如一个名为"address"的一致字段,其索引为"poco.emails.address",那么您最好指向该特定索引属性以查看它是否$exists

$conditions = array_merge($conditions, [
  'owner.$id' => $this->getId(),
  'poco.name.familyName' => "Smith",
  'poco.emails.0.address' => array( '$exists' => FALSE )
]);

但如果数组纯粹由"值组成"只有和没有"子文档",然后只是测试最初演示的数组的0索引位置就足够了。