您需要按以下顺序列出的文档:
- 其中 foo = "橙色"
- 其中bar =“橙色”
- 其中baz =“橙色”
这不能用单个 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”而不是“foo”、“bar”、“baz”
有关聚合的更多信息,请参阅http://docs.mongodb.org/manual/reference/aggregation和http://docs.mongodb.org/manual/tutorial/aggregation-examples/