Reputation: 36620
I am trying to randomly obtain random a document from a collection which I already achieved successfully with the following code:
const username = 'willem';
db.db(MDBC.db).collection(MDBC.pC).aggregate([{ $sample: { size: 1 } }]).next((err, doc) => {console.log(doc)});
However I want to put a certain restriction on my random document that is selected which is the following:
The randomly selected document has a username field which cannot have a certain value, in this case 'willem'.
Upvotes: 2
Views: 1688
Reputation: 10662
You can add a new pipeline stage before getting a random document.
const username = 'willem';
db.db(MDBC.db).collection(MDBC.pC).aggregate([
{ $match: { username: { $not: { $eq: username } } } }
{ $sample: { size: 1 } }
])
.next((err, doc) => {console.log(doc)});
the match filters the documents. Here it passes all the documents that don't have the willem username to the next stage.
Upvotes: 5