聚合查询中mongo db投影内的操作

时间:2016-11-23 10:35:41

标签: node.js mongodb mongoose mongodb-query mongodb-aggregation

我正在开发搜索功能。我有一个对象包含键值对中的数据,其中键是一个对象的id,值是我用一些后台进程计算的分数。所以我的搜索论坛数据中的情况我必须添加之前用新分数计算的分数。

我正在使用聚合进行搜索操作。以下是我的代码段。

文档

 {
   "_id": ObjectId("57de00eb0b1e50fa66290198"),
   "id": "205332",
   "Title": "The relationship between bispectral index values and age in children",
   "title": "Bispectral index values during general anesthesia in children",
   "OutcomesAvailable": "No",
   "DateStart": "2011-03-10T00:00:00-06:00",
   "DateEnd": {
      "type": "actual",
      "value": "2012-05-01T00:00:00-05:00"
    },
   "DateChangeLast": "2014-07-21T11:39:54-05:00",
   "gender": "N/A",
  "highAge": NumberInt(12),
  "lowAge": 0.5,
  "recordType": "xxxxxxxx",
  "__v": NumberInt(0) 
 }  


Object containing key as document id and value as score
-------------------------------------------------------
var textSearch = 'cancer';

var test_ids = {
    '277313',
    '278237',
    '278356',
    '278547' 
 }

 scoresArr = { 
  '277313': '79.06410256410257',
  '278237': '65.27777777777777',
  '278356': '66.83928571428572',
  '278547': '66.8051948051948' 
}

我的查询,我想在新搜索得分中添加上述对象的得分。

var aggregation = TestCollection.aggregate(
        [{
                $match: {
                    $and: [
                            {
                                "id": {
                                    $in : test_ids
                                }
                            }, 
                            {
                                $text: {$search: textSearch}
                            }
                        ]
                }
            }, {
                $sort: {
                    score: {
                        $meta: "textScore"
                    }
                }
            }, {
                $project: {
                    id: 1,
                    scoreText: {
                        $meta: "textScore"
                    },
                    score: {
                        $add: [{
                            $cond: ["$scoreText", {
                                $meta: "textScore"
                            }, {
                                $meta: "textScore"
                            }]
                        }, 
                        {
                            $cond: [{
                                $gte: [scoresArr["$id"], 0]
                            },
                            scoresArr["$id"],
                            scoresArr["$id"]
                        ]},
                        ]
                    }
                }
            }, {
                $sort: {
                    score: -1
                }
            }
        ]
    ); 

aggregation.exec(function(err, data) {
    // here you will get output
});

我得分为零。我知道我这样做的方式不对。请帮我解决这个问题。

由于

0 个答案:

没有答案