Mongo使用带排序的索引

Bri*_*ong 2 mongodb mongoid

我正在尝试优化mongodb查询.我有一个指标from_account_id,to_account_idcreated_at.但是以下查询执行完整集合扫描.

{
    "ts": {
        "$date": "2012-03-18T20:29:27.038Z"
    },
    "op": "query",
    "ns": "heroku_app2281692.transactions",
    "query": {
        "$query": {
            "$or": [
                {
                    "from_account_id": {
                        "$oid": "4f55968921fcaf0001000005"
                    }
                },
                {
                    "to_account_id": {
                        "$oid": "4f55968921fcaf0001000005"
                    }
                }
            ]
        },
        "$orderby": {
            "created_at": -1
        }
    },
    "ntoreturn": 25,
    "nscanned": 2643718,
    "responseLength": 20,
    "millis": 10499,
    "client": "10.64.141.77",
    "user": "heroku_app2281692"
}
Run Code Online (Sandbox Code Playgroud)

如果我不做or,只查询from_account_idto_account_id订单,它很快.

获得理想效果的最佳方法是什么?我应该像一个数组一样在一个字段中保留account_ids(来自和来自)或许还有更好的方法.谢谢!

jar*_*red 7

不幸的是,正如您所发现的,$或子句可能会使优化器的生命变得困难.

所以,要解决这个问题,你有几个选择.其中:

  • 将您的查询分为两个并手动合并结果.
  • 更改数据模型以允许高效查询.例如,您可以添加"referenced_accounts"字段,该字段是事务中引用的所有帐户的数组.