我希望根据哪个字段匹配对结果进行排序。 鉴于我有一个包含这样的文档的集合:
{
"foo": "orange",
"bar": "apple",
"baz": "pear",
}
{
"foo": "kiwi",
"bar": "orange",
"baz": "banana",
}
如何在foo,bar或baz中匹配“orange”的文档按其匹配的字段对结果进行排序,即所有与字段foo匹配的文档应出现在字段栏中的文档之前的结果中。 ?
谢谢!
答案 0 :(得分:0)
尝试以下查询:
db.test.find({$or:[{'foo':"orange"},{'bar':"orange"}]}).sort({'foo':-1,'bar':-1})
答案 1 :(得分:0)
您需要按以下顺序列出文档:
使用单个find()。sort()命令无法完成此操作,因为无法按字段的键(名称)排序,只能按其内容进行排序。
但是,有可能使用aggregate():
> 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/