过滤结果最佳匹配结果在顶部,然后跟随其余的结果



我正在开发一个城市过滤器mongodb和nodejs与城市列表与这样的复选框

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

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

var query = {city:{ $in:city }};
 posts.find(query, {} , function(e,docs){
            res.json(docs);
  });

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

1。假设如果我选择了任何一个1或2的城市,那么这个城市的结果首先显示,剩下的城市紧随其后,即使那些城市没有被选中。

谢谢。

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 :) 

最新更新