过滤结果最佳匹配结果,然后按照剩余结果

时间:2015-09-24 05:06:08

标签: node.js mongodb sorting express mongoose

我正在使用mongodb和nodejs开发一个城市过滤器,其中包含带有此类复选框的城市列表

  • 城市名称1
  • 城市名称2
  • 城市名称3
  • 城市名称4

一旦我们点击任何城市或多个城市,我们就会收到与该城市相关的数据,并附有以下代码。

var query = {city:{ $in:city }};

 posts.find(query, {} , function(e,docs){
            res.json(docs);
  });

通过查询我只是将城市作为数组传递并接收数据。但我的要求是:

1.如果我选择了任何1或2个城市,那么即使这个城市未被选中,该城市结果也会先到,而剩下的城市会跟随该城市。

感谢。

1 个答案:

答案 0 :(得分:0)

Query1 : db.city.find({name:{$in:["Bangalore"]}})
Query2 - db.city.find({name:{$nin:["Bangalore"]}})

**

 - Edit

**

> var result = []; //Define an empty Array
> var cur = db.city.aggregate([{$match:{name:{$in:["Bangalore","Delhi"]}}}]); //Get matching city and save it in cursor
> while(cur.hasNext()){   result.push(cur.next()) } // Retrieve the cursor data and push it in array  
> var cur = db.city.aggregate([{$match:{name:{$nin:["Bangalore","Delhi"]}}}]); // Get non matching city and save it in cursor (should be new variable)
> while(cur.hasNext()){   result.push(cur.next()) }
> for(var i=0;i<result.length;i++){printjson(result[i])}

This will give you expected result. Hope you are expecting the same :)