如何将$match与条件 if-else 一起使用?



所以我想在if councilPeriod not equal to 1 i can use condition where person with same families_id in other person families array showing up else that condition disabled的地方进行条件查询。

const families = await People.aggregate([
{
$unwind: {
path: '$families'
}
},
{ $project: { Ids: '$families._id' } }
]);
const families_id = families.map(function(i) {
return i.Ids;
});
const people = await People.aggregate([
{
$project: {
_id: 1,
nia: 1,
name: 1,
address: 1,
sector: 1,
status: 1,
grazing: 1,
councilPeriod: 1,
crtdDiff: { $subtract: [new Date(), '$dateJoined'] },
sidiDiff: { $subtract: [new Date(), '$dateSidi'] }
}
},
{
$match: {
status: 'Active',
_id: { $nin: families_id },
grazing: 'Tidak',
councilPeriod: { $ne: 1 },
crtdDiff: { $gt: 63072000000 },
sidiDiff: { $gt: 63072000000 }
}
}
]);

我希望有一个查询,如果理事会期间不等于 1,那么家庭也会出现,否则相反。谢谢。

您可以在聚合中使用 if 条件,例如 ,

db.inventory.aggregate(
[
{
$project:
{
item: 1,
discount:
{
$cond: { if: { $ne: [ "$councilPeriod", 1 ] }, then: _anyCondition_, 
else: _anyCondition_ }
}
}
}
]
)

希望你觉得有用.

最新更新