1

Azure functions:

    module.exports = async function (context, req) {
        await client.connect();
        const database = client.db("crud");
        const collection = database.collection("moments");
        let obj = await collection.aggregate([{$sample:{ size: 3 }}]).toArray();
        if (!obj) {
            return context.res = {
                status: 400,
                body: "not found"
            };
        }
        return context.res = {
            status: 200, /* Defaults to 200 */
            body: obj
        };
    }

I am getting the same records each time (first 3) from the db.collection.

If query without the toArray() method, returns:


{
  "_events": {},
  "_eventsCount": 0
}

which I can't seem to find why.

  • please describe more about your problem, I can't understand the main problem and issue :( – nima Aug 20 '21 at 08:23
  • $sample should work and return the random documents if the pre-conditions are met as mentioned in the official document. However it seems a bug from Azure Cosmos DB as per the GitHub issue: https://github.com/MicrosoftDocs/azure-docs/issues/10382. I am trying to connect internally with product team to check the current status on it. However, as a workaround you can generate a random value and retrieve the documents as mentioned in the thread: https://stackoverflow.com/questions/2824157/random-record-from-mongodb. – AnuragSharma-MSFT Aug 23 '21 at 16:59

2 Answers2

0

$sample is still not working as expected with Azure Cosmos DB MongoDB API and should be fixed in near future, however we can use something like below to get random list of document:

db.collection.find().limit(3).skip(Math.random()*db.collection.count())

Finding a random document in MongoDB

0

Seems like it's a bug from Azure Cosmo DB as mentioned by AnuragSharma.

Managed a manual workaround by using the collections count and Math.random.

ouflak
  • 2,458
  • 10
  • 44
  • 49