2015-09-24 33 views
0

我開發MongoDB中一個城市的過濾器,並與城市的名單的NodeJS與複選框這樣過濾器在頂部結果生成最佳匹配結果,然後按照其餘結果

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

一旦我們點擊任何城市或多個城市,然後我們收到的數據與相關THA以下代碼。

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

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

通過查詢我只是通過城市作爲陣列和接收Data..But我的要求是:

1.Suppose如果我選擇任何1或2個城市然後該城市來結果第一和剩餘的城市即使那些城市未被選中,也會跟隨該城市。

謝謝。

+0

能否提供城市的樣本文件? –

+0

http://puu.sh/kma6N/0a94e633a7.png你可以帶任何一個城市,我附上了一個截圖...... –

+0

我不知道是否有可能從一個查詢。爲什麼您可以嘗試執行2個單獨的查詢並將結果保存在一個結果集中。 –

回答

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

我試試這個...我需要一個結果,其中$ nin數組內容後顯示數組中的第一個結果$ .. 。我們也可以通過這個查詢{city:{$ in:city}},{city:{$ nin:city}}但我主要關心排序順序.. –

+0

我明白你的關注,我不確定你在nodejs中做,但在java中我會有一個arraylist,我會執行這2個查詢順序,並添加到arraylist維護插入順序。希望它會幫助:) –

+0

謝謝,我會試試這個... –