使用$ or选择器排序,并使用/ db / _find进行工作索引

时间:2019-01-24 16:33:10

标签: javascript couchdb cloudant couchdb-mango

背景:我在数据库中有文件。所有文档都具有字段typeasset_type。我想获取type assetasset_type database的所有文档。有些文档的“分数”字段带有值,而有些则没有此字段。我还想按score字段的降序或升序排序。

我包括了$ or选择器,因为sort需要在选择器以及索引中具有sorted字段。由于无论是否具有score字段,我都需要所有文档,因此我使用了这种hacky方法。

这是我的许多尝试之一:

let params = {
    'selector': {
        'type': 'asset',
        'asset_type': 'database',
        $or: [
            {'score': {'$exists': true}},
            {'score': {'$exists': false}}
        ]
    },
    'use_index': 'scoreSorted'
  };

if (descending) {
    params.sort = [{'score': 'desc'}];
} else {
    params.sort = [{'score': 'asc'}];
}

db.find(params, (err, body) => {
    doSomething(body);
});

索引:

{
  "index": {
    "fields": [
      "score"
    ]
  },
  "type": "json",
  "ddoc": "scoreSorted"
}

示例文档:

{
  "_id": "sample_doc1",
  "type": "asset",
  "asset_type": "database",
  "score": 62345
}, 
{
  "_id": "sample_doc2",
  "type": "asset",
  "asset_type": "database"
},
{
  "_id": "sample_doc3",
  "type": "asset",
  "asset_type": "database",
  "score": -2512
}

这产生的是type assetasset_type database的文档,但是它们没有按score排序,而是按{{ 1}}。响应中还包含警告_id

我已经在文档中进行了广泛搜索,但是找不到解决方法。

有人可以为我指出一个按预期工作的解决方案吗?

0 个答案:

没有答案