mongoose "Find" with multiple conditions
Solution 1:
app.get('/user',function(req, res) {
User.find({region: "NA",sector:"Some Sector"}, function(err, user)
{
if (err)
{
res.send(err);
}
console.log(user);
res.json(user);
});
});
If you want data with either region:"NA" or sector:"Some Sector". you can use $or
operator.
User.find({$or:[{region: "NA"},{sector:"Some Sector"}]}, function(err, user)
{
if (err)
{
res.send(err);
}
console.log(user);
res.json(user);
});
Solution 2:
If you want results that contain any region or sector as long as both are present at the same time you need the following query in your User.find
:
{region: {$exists:true},sector: {$exists:true}}
,
is the equivalent of $and
as long as you are searching different fields.
Solution 3:
const dateBetweenDates = await Model.find({
$or: [
{
$and: [
{ From: { $gte: DateFrom } },
{ To: { $lte: DateTo } },
], // and operator body finishes
},
{ _id: req.user.id},
], //Or operator body finishes
})
Solution 4:
For anyone else trying to find with multiple conditions using mongoose, here is the code using async/await.
app.get('/user', async (req, res) {
const user = await User.find({region: "NA",sector:"Some Sector"});
if (user) {
// DO YOUR THING
}
});
Solution 5:
Multiple conditions
$lt selects the documents where the value of the field is less than (i.e. <) the specified value.
For most data types, comparison operators only perform comparisons on fields where the BSON type matches the query value's type. MongoDB supports limited cross-BSON comparison through Type Bracketing.
const users = await User.find({ region: "NA", age: { $lt: 30 } });