问题描述
让我说我有1000个文档,每个文档都有:
lets say I have 1000 documents where each one has:
user_id
text
现在,我想提取所有这些文档,但首先要从几个特定用户(给定用户ID数组)中提取文档,然后再提取其余所有文档.
Now, I would like to pull all those documents but first pull the documents from a few specific users (given an array of user ids) and then all the rest.
如果要在特定用户数组中存在user_id(使用范围传递该数组),然后使用map reduce来创建一个新的权重内联属性,然后对该新属性进行排序.但是据我了解,您无法对map reduce进行排序.
I was thinking to use map reduce to create a new weight inline attribute if the user_id exists in the specific users array (using scope to pass the array) and then to sort that new attribute. But from what I could understand, you can not sort after map reduce.
任何人都有一个好的建议如何实现这一目标?任何建议都将受到欢迎.
Any one has a good suggestion how to pull this off? Any suggestion will be welcome.
谢谢!
推荐答案
这里没有很多细节,但是我可以给出一个示例案例进行考虑.考虑以下文档集:
Well there isn't a lot of detail here, but I can give a sample case for consideration. Consider the following set of documents:
{ "user" : "fred", "color" : "black" }
{ "user" : "bill", "color" : "blue" }
{ "user" : "ted", "color" : "red" }
{ "user" : "ted", "color" : "black" }
{ "user" : "fred", "color" : "blue" }
{ "user" : "bill", "color" : "red" }
{ "user" : "bill", "color" : "orange" }
{ "user" : "fred", "color" : "orange" }
{ "user" : "ted", "color" : "orange" }
{ "user" : "ally", "color" : "orange" }
{ "user" : "alice", "color" : "orange" }
{ "user" : "alice", "color" : "red" }
{ "user" : "bill", "color" : "purple" }
因此,假设您想冒泡将用户的项目比尔"和"ted"放在结果的顶部,然后将其他所有内容按user
和color
排序.您可以做的是通过 $ project 阶段运行文档汇总如下:
So suppose you want to bubble the items for the users "bill" and "ted" to the top of your results, then everything else sorted by the user
and the color
. What you can do is run the documents through a $project stage in aggregate, as follows:
db.bubble.aggregate([
// Project selects the fields to show, and we add a weight value
{$project: {
_id: 0,
"user": 1,
"color": 1,
"weight": {$cond:[
{$or: [
{$eq: ["$user","bill"]},
{$eq: ["$user","ted"]}
]},
1,
0
]}
}},
// Then sort the results with the `weight` first, then `user` and `color`
{$sort: { weight: -1, user: 1, color: 1 }}
])
因此,根据user
是否与所需值之一匹配,有条件地为weight
分配了一个值.不匹配的文档仅被赋予0
值.
So what that does is conditionally assign a value to weight
based on whether the user
was matched to one of the required values. Documents that do not match are simply given a 0
value.
当我们将此经过修改的文档移至 $ sort 阶段,可以使用新的weight
键对结果进行排序,以使加权"文档位于顶部,然后再进行其他操作.
When we move this modified document on to the $sort phase, the new weight
key can be used to order the results so the "weighted" documents are on top, and anything else will then follow.
您可以对 $ project $ project 这样的重量.有关更多信息,请参见操作员参考:
There a quite a few things you can do to $project a weight in this way. See the operator reference for more information:
http://docs.mongodb.org/manual/reference/operator/aggregation /
这篇关于mongodb:获取特定文档然后再获取其余文档的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!