1

I am trying to query my document which looks like this

"approvals" : {
    "REV" : "",
    "SS" : "",
    "ABC" : {
        "status" : "Sent for approval",
        "approved_at" : "",
        "approved_by" : "",
    },
    "XYZ" : {
        "status" : "Approved",
        "approved_by" : "[email protected]",
        "approved_at" : ISODate("2020-01-06T09:48:22.777Z"),
    },....
}

The Approval object can have multiple sub documents like ABC,XYZ...etc, I need to query if this "approval" has any sub document whose "status" is not in APPROVED state

1
  • I am using MongoDb 2.6.10 Commented Jan 6, 2020 at 11:45

1 Answer 1

1

You need to run $objectToArray to scan your dynamic keys. Then you need $anyElementTrue with $map to check if there's any Approved value:

db.collection.find(
    { 
        $expr: { 
            $anyElementTrue: { 
                $map: { 
                    input: { $objectToArray: "$approvals" },
                    in: { $ne: [ "$$this.v.status", "Approved" ] } 
                }
            } 
        }
})

Mongo Playground

Sign up to request clarification or add additional context in comments.

2 Comments

Getting Error: error: { "$err" : "Can't canonicalize query: BadValue unknown top level operator: $expr", "code" : 17287 }
@Odin you need to upgrade your MongoDB server at least to 3.4.4 since you need $objectToArray as the only way to dynamically read values when keys are unknown

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.