Willem van der Veen
Willem van der Veen

Reputation: 36620

MongoDB exclude certain documents from aggregation

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

Answers (1)

Ramesh Reddy
Ramesh Reddy

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

Related Questions