【问题标题】:MongoDB select random 5 documents via find queryMongoDB 通过查找查询随机选择 5 个文档
【发布时间】:2019-07-18 15:29:13
【问题描述】:

我需要使用 find 函数从 mongoDB 中随机找到 5 个文档。我使用 LoopBack 4 框架。我已经尝试使用示例(在评论中)

 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[];

【问题讨论】:

标签: javascript node.js mongodb loopback loopback4


【解决方案1】:

我不熟悉 Loopback,但是使用纯节点和节点 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()
}()

在包含从 0 到 99 的 _id 的集合中,这将随机输出 5 个 _id 大于 50 的文档。示例输出:

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

您需要让上面的示例与 Loopback 一起使用,但基本的想法就在那里。

注意:

您需要aggregation 而不是find()

阅读$sample documentation 并特别注意它的behavior

$sample 使用两种方法之一来获取 N 个随机文档,具体取决于集合的大小、N 的大小以及 $sample 在管道中的位置。

$sample 在管道中的位置很重要。如果您需要通过$match 阶段选择集合的一个子集来执行$sample(如上面的示例),那么您需要确保要采样的子集在16 MB 以内(限制为MongoDB 内存中排序)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-11
    • 2018-09-04
    • 1970-01-01
    相关资源
    最近更新 更多