mongodb按字段匹配排序 [英] mongodb sort by match in field
问题描述
我希望根据匹配的字段对结果进行排序.鉴于我有一个包含这样的文档的集合:
I'm look to sort results based on in which field matches. Given I have a collection with documents like this:
{
"foo": "orange",
"bar": "apple",
"baz": "pear",
}
{
"foo": "kiwi",
"bar": "orange",
"baz": "banana",
}
如何根据匹配的字段对在 foo、bar 或 baz 中匹配orange"的文档的结果进行排序,即在字段 foo 上匹配的所有文档应出现在字段 bar 等中的文档之前的结果中.?
How can I sort a result for documents matching "orange" in either foo, bar, or baz by the field in which they match, i.e. all documents matching on field foo should appear in the result before documents in field bar etc.?
谢谢!
推荐答案
您需要按以下顺序排列的文档列表:
You want a list of documents in the following order:
- where foo = "orange"
- where bar = "orange"
- where baz = "orange"
这不能通过单个 find().sort() 命令完成,因为无法按字段的键(名称)排序,只能按其内容排序.
This can not be done with a single find().sort() command, because there is no way to sort by the key (name) of a field, only by it's content.
不过,使用aggregate() 是可能的:
It is possible, though, with an 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
}
你是对的,如果你认为聚合太复杂了.如果您的数据以不同的方式组织会更容易,例如
You're right, if you think that is aggregate is too complicated. It would be easier if your data were organized differently, something like
{ type: "foo", value: "orange" }
并使类型名称可排序 - 如ba1"、ba2"、ba3"而不是foo"、bar"、baz"
and have the type names sortable - like "ba1","ba2","ba3" instead of "foo","bar","baz"
有关聚合的更多信息,请参阅http://docs.mongodb.org/manual/reference/aggregation 和 http://docs.mongodb.org/manual/tutorial/aggregation-examples/
For more information on aggregate, see http://docs.mongodb.org/manual/reference/aggregation and http://docs.mongodb.org/manual/tutorial/aggregation-examples/
这篇关于mongodb按字段匹配排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!