doudiejian5827 2016-09-23 11:25
浏览 110
已采纳

查询时间戳字段比使用PHP的MongoDB中的另一个时间戳字段更旧

How can I obtain an object from a MongoDB collection where a specific field1 (timestamp or date) is older/newer than another specific field2 (timestamp or date)?

Given the following example object:

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

This object should match a query like: where export.active is true and updated_on > export.last_exported_on

I've tried it with the aggregation framework, since I've read that $where can be very slow, but without any success.

// 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]
]);

I can change timestamps into date or anything else, but I don't see the problem in the type.

Edit: Not all objects have the last_exported_on or the export fields at all. Besides that both can be null or empty or 000000.

  • 写回答

1条回答 默认 最新

  • doukesou4452 2016-09-23 11:42
    关注

    That's because after you do the $project you end up only with the dst and _id fields, so you cannot $match on export.active. You need to match on export.active before the projection. After that you need another match on the dst field.

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

    Edit

    Alternatively, you can make sure to preserve export.active and to spare another $match:

    [
        {
            $project: {
                "export.active": 1,
                cmp: {
                    $cmp: [
                        "$updated_on",
                        "$export.last_exported_on"
                    ]
                }
            }
        },
        {
            $match: {
                cmp: 1,
                "export.active": true
            }
        }
    ]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP