你想要的文件,按以下順序列表:
- 其中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/aggregation和http://docs.mongodb.org/manual/tutorial/aggregation-examples/
這是爲你工作? – Sach 2013-03-17 12:35:21