使用PHP查询MongoDB中哪个时间戳字段比另一个时间戳字段早


Query where timestamp field is older than another timestamp field in MongoDB with PHP

我如何从MongoDB集合中获得一个对象,其中特定字段d1(时间戳或日期)比另一个特定字段d2(时间戳或日期)更旧/新?

给定下面的例子对象:

// MongoDB 3.2
{
  name: 'test',
  updated_on: Timestamp(1474416000, 0),
  export: {
    active: true,
    last_exported_on: Timestamp(1474329600, 0)
  }
}

该对象应该匹配如下查询:where export.active is true and updated_on > export.last_exported_on

我已经在聚合框架中尝试了它,因为我读到$where可能非常慢,但没有任何成功。

// PHP 5.4 (and MongoDB PHP lib. http://mongodb.github.io/mongo-php-library)
$collection->aggregate([
  ['$project' => [
    'dst' => ['$cmp' => ['updated_on', 'export.last_exported_on']],
    'name' => true
  ]],
  ['$match' => ['dst' => ['$gt' => 0], 'export.active' => ['$eq' => true]]],
  ['$limit' => 1]
]);

我可以将时间戳更改为日期或其他任何内容,但我不认为类型有问题。

编辑:不是所有的对象都有last_exported_onexport字段。此外,两者都可以为null或空或000000

这是因为在您做$project之后,您最终只使用dst_id字段,因此您不能在export.active$match。你需要在投影前匹配export.active。之后,您需要在dst字段上进行另一个匹配。

[
    {
        $match: {
            "export.active": true
        }
    },
    {
        $project: {
            dst: {
                $cmp: [
                    "$updated_on",
                    "$export.last_exported_on"
                ]
            }
        }
    },
    {
        $match: {
            dst: 1
        }
    }
]

编辑

或者,您可以确保保留export.active并保留另一个$match:

[
    {
        $project: {
            "export.active": 1,
            cmp: {
                $cmp: [
                    "$updated_on",
                    "$export.last_exported_on"
                ]
            }
        }
    },
    {
        $match: {
            cmp: 1,
            "export.active": true
        }
    }
]