0
votes

I'm using azure cosmos DB acting as MongoDB version 4.0.0. I need to get N random documents from Azure Cosmos DB using the MongoDB API. I've tried using the $sample operator but it is giving me documents in the same order each time I query.

db.collectionName.aggregate([{$sample: {size: 1}}])

No matter how many times I run this query I'm getting the same document from the collection.

1
what is the version you are using - Sajeetharan
MongoDB server version 4.0.0 and MongoDB shell version 3.6.8 - Ajay Theetharappan
I tested in my side and met the same question, the same when writing code to test. - Tiny Wang
That seems to be a bug, I've tested with new database/collection, I also test in a collection with more than 100 documents, all no luck. But it's true that some others successful. - Tiny Wang

1 Answers

0
votes

I can't find any document on how $sample execute, but I think the problem we met may have relationship with what mentioned here. That means if some conditions are not met, it will get the result and sort them, then return the size count of items. So what we get always the same. I'll try to find more details, and any further find will update.

enter image description here