Home > database >  Mongo Aggregate JS 'every' equivalent
Mongo Aggregate JS 'every' equivalent

Time:01-03

I'm using an aggregate and I'd like to add a Boolean property per Document for if all properties in a subArray on the Document are true.

In my example below...CONFLICTS is a subArray of Docs that each contain a Boolean property called Resolved. I just want to add a new allResolved field for if all Conflicts are resolved.

So..in my addFields stage, I have something like

 {
   '$project': {
      'allResolved': {
        '$allElementsTrue': '$CONFLICTS.resolved'
      }, 
    }
  }

so JS equivalent is const allResolved = CONFLICTS.every(conflict => conflict.resolved)

But this seems to always return true which is not correct

CodePudding user response:

Query

  • this does extra checks
  • check to be array
  • to be not empty array
  • and each member to be true (missing and nulls will be false)

Test code here

aggregate(
[{"$set":
  {"allResolved":
   {"$and":
    [{"$isArray":["$conflicts"]},
     {"$not":[{"$eq":["$conflicts", []]}]},
     {"$reduce":
      {"input":"$conflicts",
       "initialValue":true,
       "in":
       {"$and":[{"$eq":["$$this.Resolved", true]}, "$$value"]}}}]}}}])
  • Related