简体   繁体   English

MongoDB通过查找查询随机选择5个文档

[英]MongoDB select random 5 documents via find query

I need to find random 5 documents from mongoDB by using find function. 我需要使用查找功能从mongoDB中随机查找5个文档。 I using LoopBack 4 framework. 我使用LoopBack 4框架。 I already try to use sample (it is in comment) 我已经尝试使用示例(在评论中)

 const userParties: IndividualParty[] = (await find(
            this.logger,
            {
                where: {
                    and: [
                        { _id: { nin: ids.map(id => id) } },
                        { gender: { inq: gender } },
                    ],
                },
                //sample: { size: 5 },
                //limit: 5,
            } as Filter<IndividualParty>,
            this.partyRepository,
        )) as IndividualParty[];

I'm not familiar with Loopback, but using pure node and node MongoDB driver, here's the shortest example I can come up with: 我不熟悉回送,但是使用纯节点和节点MongoDB驱动程序,这是我能想到的最短的示例:

var run = async function() {
  const conn = await require('mongodb').MongoClient.connect('mongodb://localhost:27017', {useNewUrlParser: true})
  let agg = [
    {'$match': {'_id': {'$gte': 50}}},
    {'$sample': {'size': 5}}
  ]
  let res = await conn.db('test').collection('test').aggregate(agg).toArray()
  console.log(res)
  await conn.close()
}()

In a collection containing _id from 0 to 99, this will randomly output 5 documents having _id larger than 50. Example output: 在包含从0到99的_id的集合中,这将随机输出_id大于50的5个文档。示例输出:

[ { _id: 60 }, { _id: 77 }, { _id: 84 }, { _id: 96 }, { _id: 63 } ]

You would need to make the above example work with Loopback, but the basic idea is there. 您需要使上面的示例与Loopback一起使用,但是基本思想就在那里。

Note: 注意:

You need aggregation instead of find() . 您需要聚合而不是find()

Have a read through the $sample documentation and note especially its behavior : 通读$ sample文档 ,特别注意其行为

$sample uses one of two methods to obtain N random documents, depending on the size of the collection, the size of N, and $sample's position in the pipeline. $ sample使用两种方法之一来获取N个随机文档,具体取决于集合的大小,N的大小以及$ sample在管道中的位置。

The position of $sample in the pipeline is important. $sample在管道中的位置很重要。 If you need to select a subset of the collection to do $sample on via a $match stage (as with the example above), then you will need to ensure that the subset to be sampled is within 16 MB (the limit of MongoDB in-memory sort). 如果您需要选择集合的一个子集以通过$match阶段进行$sample (如上例所示),则需要确保要采样的子集在16 MB以内(MongoDB在-内存排序)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM