Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: Check for array for object and if exists return true, otherwise false

I'm trying to query an array within a collection and project the value "true" if the object exists within the array. If the object doesn't exist within the array, project "false". I am working within MongoDB and I'm not too familiar with it.

In my scenario, I have two collections that I am working with. I am aggregating a collection of 'staff' members and I am performing a $lookup function to a collection of 'businesses'. Within 'businesses' I have an array of the businesses capabilities.

For example, I have staff collection

staff = [
  ...
  {_id: 1, businessId: 11},
  {_id: 2, businessId: 22},
  ....
]

Businesses collection

businesses = [
  ...
  {_id: 11, capabilities: ["claiming", "pushing"]},
  {_id: 22, capabilities: ["claiming", "popping"]},
  ....
]

And have a $lookup setup like

db.getCollection('staff').aggregate([
    {
        $lookup:
            {
                from: "businesses",
                localField: "businessId",
                foreignField: "_id",
                as: "business_Info"
            }
    },

How can I $project per staff member to a value like $canClaim: true, if "claiming" appears within "capabilities"?

like image 726
Maandeep Avatar asked Mar 04 '23 00:03

Maandeep


1 Answers

You can use $in aggregation operator to check whether the array contains the value or not.

db.getCollection("staff").aggregate([
  { "$lookup": {
    "from": "businesses",
    "localField": "businessId",
    "foreignField": "_id",
    "as": "business_Info"
  }},
  { "$unwind": "$business_Info" },
  { "$addFields": {
    "canClaim": { "$in": ["claiming", "$business_Info.capabilities"] }
  }}
])

MongoPlayground

like image 115
Ashh Avatar answered Mar 06 '23 22:03

Ashh