mongo db聚合随机化(随机播放)结果

编程入门 行业动态 更新时间:2024-10-27 04:30:17
本文介绍了mongo db聚合随机化(随机播放)结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在浏览一堆mongo文档,找不到改组或随机分配结果内容的可能性

I was going thru bunch of mongo docs and can't find a possibility to shuffle or randomize result content

有吗?

推荐答案

专门针对聚合框架本身,实际上并没有任何本机方式,因为尚无可用的运算符来执行类似生成随机数的操作.因此,由于缺少不断变化的种子值,因此您可以投影出要排序的字段的任何匹配都不会是真正随机的".

Specifically for the aggregation framework itself there is not really any native way as there is no available operator as yet to do something like generate a random number. So whatever match you could possibly project a field to sort on would not be "truly random" for lack of a shifting seed value.

更好的方法是在返回结果后将结果作为数组洗牌".有多种随机播放"实现,以下是JavaScript的一种实现:

The better approach is to "shuffle" the results as an array after the result is returned. There are various "shuffle" implementations, here is one for JavaScript:

function shuffle(array) { var currentIndex = array.length , temporaryValue , randomIndex ; while (0 !== currentIndex) { randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; temporaryValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = temporaryValue; } return array; }

但是,如果您实际上是在谈论改组大量结果,例如使用新的 $ out 操作符或实际上的任何集合,然后可以使用mapReduce作弊".

But if you are actually talking about shuffling a large number of results such as in a collection obtained from use of the new $out operator or any collection in fact, then you can "cheat" by using mapReduce.

db.collection.mapReduce( function(){ var random = Math.floor( Math.random() * 100000 ); emit({ rand: random, id: this._id }, this ); }, function(){}, { out: { replace: "newcollection" } } );

这利用了mapReduce的特性,因为键值始终被排序.因此,通过将随机数作为密钥的开头部分,您将始终获得随机排序的结果.

This takes advantage of the nature of mapReduce in that the key value is always sorted. So by including a random number as the leading part of the key then you will always get a random ordered result.

更多推荐

mongo db聚合随机化(随机播放)结果

本文发布于:2023-10-28 08:16:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1536065.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:随机化   mongo   db

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!