简体   繁体   中英

Mongo Aggregate JS 'every' equivalent

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

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"]}}}]}}}])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM