Home > OS >  How to Combine To Queries With MongoDB Operators?
How to Combine To Queries With MongoDB Operators?

Time:10-08

I have these two search expressions. I was wandering how I could combine these two into one expression using maybe $or or $and operators using Mongoose.

Here is the code:

const mailContent = await Mail.find({ sender: id, receivers: { $elemMatch: { $eq: req.user._id } } }).populate('sender');
const outMailContent = await Mail.find({ sender: req.user._id, receivers: { $elemMatch: { $eq: id } }, type: {$not:{$eq: 'offer'}} }).populate('sender');

Thanks in advance!

CodePudding user response:

By using $or

const mailContent = await Mail.find(
  { $or:[
    { sender: id, receivers: { $elemMatch: { $eq: req.user._id } } },
    { sender: req.user._id, receivers: { $elemMatch: { $eq: id } }, type: {$not:{$eq: 'offer'}} }
  ] }
).populate('sender');
  • Related