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"?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With