简体   繁体   中英

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'.

Hmm, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM