我正在使用 MongoDB 构建一个非常奇特的“趋势”帖子算法。由于该算法会消耗大量时间,因此我在 cron 任务中执行我的算法,然后缓存一个已排序的帖子 ID 数组。像这样(PHP vardump):
"trending" => array("548ac5ce05ea675e468b4966", "5469c6d5039069a5030041a7", ...)
关键是我找不到任何方法来使用 MongoDB 按该顺序检索它们。 使用 MySQL 只需执行以下操作即可完成:
SELECT * FROM posts
ORDER BY FIELD(_id, '548ac5ce05ea675e468b4966', '5469c6d5039069a5030041a7',...)
到目前为止我尝试的是可以找到的here ,所以现在我可以检索带有权重的排序列表,但不能检索帖子。响应是这样的:
{
"result" : [
{
"_id" : ObjectId("548ac5ce05ea675e468b4966"),
"weight" : 1
},
{
"_id" : ObjectId("5469c6d5039069a5030041a7"),
"weight" : 2
}
],
"ok" : 1
}
有没有人做到了这一点,甚至不知道从哪里开始?
谢谢!
最佳答案
我来自您链接的 SO 帖子。我发现的是使用 MongoDB 提供的 $$ROOT 变量。
我的代码是这样的:
var ids = [456, 123, 789]
, stack = []
;
// Note that `i` is decremented here, not incremented like
// in the linked SO post. I think they have a typo.
for (var i = ids.length-1; i > 0; i--) {
var rec = {
$cond: [
{$eq: ['$_id', ids[i - 1]]},
i
]
};
if (stack.length === 0) {
rec.$cond.push(i + 1);
}
else {
var lval = stack.pop();
rec.$cond.push(lval);
}
stack.push(rec);
}
var pipeline = [
{$match: {
_id: {$in: ids}
}},
{$project: {
weight: stack[0],
data: '$$ROOT' // This will give you the whole document.
}},
{$sort: {weight: 1}}
];
Posts.aggregate(pipeline, function (err, posts) {
if (err) return next();
// Use Underscore to grab the docs stored on `data` from above.
res.json(_.pluck(posts, 'data'));
});
请注意,我个人并不完全确定构建查询的 for
循环中发生了什么。 :-P 所以大部分功劳应该归于他们。此外,我还不确定虚拟字段(如果您像我一样使用 Mongoose)是否会包含在此处,但我怀疑不会。
关于mysql - MongoDB 中带有 $in 的结果顺序类似于 MySQL 字段 ('_id' ,...),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27525235/