2013-03-08 121 views
0

我期待根據哪些字段匹配來對結果進行排序。 鑑於我有這樣與文檔的集合:mongodb按字段排序的排序

{ 
    "foo": "orange", 
    "bar": "apple", 
    "baz": "pear", 
} 

{ 
    "foo": "kiwi", 
    "bar": "orange", 
    "baz": "banana", 
} 

我如何排序在任富,酒吧,或由現場巴茲匹配「橙色」,即它們匹配的文件,即匹配所有文件的結果字段foo應該出現在字段欄等文件之前的結果中?

謝謝!

回答

0

試試下面的查詢:

db.test.find({$or:[{'foo':"orange"},{'bar':"orange"}]}).sort({'foo':-1,'bar':-1}) 
+0

這是爲你工作? – Sach 2013-03-17 12:35:21

0

你想要的文件,按以下順序列表:

  • 其中foo = 「橙色」
  • 這裏吧= 「橙色」
  • 其中baz =「orange」

Thi s不能用單個find()。sort()命令完成,因爲沒有辦法按字段的鍵(名稱)進行排序,只能通過它的內容進行排序。

這是可能的,但是,與集料():

> db.xx.find() 
{ "_id" : 1, "bar" : "apple", "baz" : "pear", "foo" : "orange" } 
{ "_id" : 2, "foo" : "banana", "bar" : "apple", "baz" : "orange" } 
{ "_id" : 3, "foo" : "banana", "bar" : "orange", "baz" : "pear" } 
{ "_id" : 4, "foo" : "banana", "bar" : "apple", "baz" : "pear" } 
{ "_id" : 5, "foo" : "orange", "bar" : "apple", "baz" : "pear" } 
>  db.xx.aggregate([ 
...   { $match: { $or: [ { foo: "orange" }, { bar: "orange" }, { baz: "orange" } ] } }, 
...   { $project: { "_id": 1, 
...      "which": { "$cond": [{ "$eq": [ "$foo", "orange" ]}, "01foo", 
...        { "$cond": [{ "$eq": [ "$bar", "orange" ]}, "02bar", "03baz" ] } 
...      ] } 
...   } }, 
...   { $group: { _id: { which: "$which", _id: "$_id" } } },   
...   { $sort: { "_id.which": 1, "_id._id": 1 } }, 
...   { $project: { which: { $substr: ["$_id.which", 2, -1] }, _id: "$_id._id" } },   
...  ]); 
{ 
    "result" : [ 
     { 
      "_id" : 1, 
      "which" : "foo" 
     }, 
     { 
      "_id" : 5, 
      "which" : "foo" 
     }, 
     { 
      "_id" : 3, 
      "which" : "bar" 
     }, 
     { 
      "_id" : 2, 
      "which" : "baz" 
     } 
    ], 
    "ok" : 1 
} 

你說的沒錯,如果你認爲是聚集太複雜了。這將是更容易,如果你的數據是不同的方式組織,像

{ type: "foo", value: "orange" } 

並具有類型名稱排序 - 樣,而不是「富」,「BA1」,「BA2」,「BA3」,「酒吧」,」巴茲」

有關聚合的更多信息,請參閱http://docs.mongodb.org/manual/reference/aggregationhttp://docs.mongodb.org/manual/tutorial/aggregation-examples/