Database
db={products:[{"_id":ObjectId("63515ad7d5f84ecbaac38f1e"),"code":"1","name":"Coca-Cola","pricePerItem":NumberInt(2),"stocks":[ObjectId("63515ad7d5f84ecbaac38f20"),ObjectId("63515b04d5f84ecbaac38f2e"),"should be excluded"]},{"_id":ObjectId("63515aeed5f84ecbaac38f24"),"code":"2","name":"Fanta","pricePerItem":NumberInt(4),"stocks":[ObjectId("63515aeed5f84ecbaac38f26")]}],stocks:[{"_id":ObjectId("63515ad7d5f84ecbaac38f20"),"count":NumberInt(10),"remaining":NumberInt(10),"costPerItem":NumberInt(1),"expireDate":ISODate("2020-12-05")},{"_id":ObjectId("63515aeed5f84ecbaac38f26"),"count":NumberInt(102),"remaining":NumberInt(10),"costPerItem":NumberInt(3),"expireDate":ISODate("2020-12-10")},{"_id":ObjectId("63515b04d5f84ecbaac38f2e"),"count":1,"remaining":0,"costPerItem":NumberInt(20),"expireDate":ISODate("2020-12-20")},{"_id":"should be excluded","count":NumberInt(10),"remaining":NumberInt(10),"costPerItem":NumberInt(1)}]}
Query
db.products.aggregate([{"$lookup":{"from":"stocks","localField":"stocks","foreignField":"_id","pipeline":[{$match:{$expr:{$and:[{$ne:[{$ifNull:["$expireDate",null]},null]},{$gt:["$remaining",0]},{$lt:[{"$dateSubtract":{"startDate":"$expireDate","unit":"day","amount":3}},"$$NOW"]}]}}}],"as":"stocksLookup"}},{$unwind:"$stocksLookup"}])