Reputation: 7736
Let say I have an array like so: [2,4,-6,-7,-3,5]
.
Is there a simple(not verbose) way of checking if an array contains a negative number in mongodb aggregation.
I will appreciate any answer. Even one that is verbose. I just prefer a less verbose one.
Upvotes: 0
Views: 835
Reputation: 2290
If you want to just filter docs that have an array-property that contains a negative number, a simple { arrayField: { $lt: 0 } }
would do.
Also if you just want to somehow categorize an array in aggregation, you could do the following.
For example, documents with schema:
{
_id: 1,
values: [2, -4, -6, -7]
}
you can add an extra boolean negative
field on the documents and filter according to that later on in aggregation results:
db.collection.aggregate([
{
$addFields: {
negative: {
$reduce: {
input: "$values",
initialValue: false,
in: {
$or: ["$$value", { $lt: ["$$this",0] }]
}
}
}
}
}
])
Upvotes: 1