Watch keynotes and sessions from MongoDB.live, our virtual developer conference.

Return Objects containing search query in array

Hey everyone, first off thanks for the help on this one. So I have attached a screen shot of a data sample we are trying to query. This budgetgroup contains a couple fields which references a user object Id. The fields are: budgetOwner (single user Object Id), approvers (array of user object ids), and members (array of user objectIds). I am trying to develop a single database query that will return an array of budget groups in which contain a specific user object ID in either the budgetOwner field, or within the two arrays (approvers & members).

Any help on this one would be greatly appreciated.

Regards,

David

Greenshot 2020-04-26 18.36.43

This query will do using the $or query operator:

userId = ObjectId("5ea6511bf82c44599b1c5ae4")    // for, example

db.collection.find(
    { $or: [ { budgetOwner: userId }, { approvers: userId }, { members: userId } ] }
)

In case you are querying such that the userId is in both the members & approvers arrays, the query is:

db.collection.find(
    { $or: [ { budgetOwner: userId }, 
             { $and: [ { approvers: userId }, { members: userId } ] }
    ] }
)

Prasad_Saya! Thank you so much! That works!

David