首页 > 解决方案 > MongoDb聚合检查对象数组中是否存在id

问题描述

我已经写了这个聚合,它工作正常

db.ParcelStatus.aggregate([{
     {
         $lookup: {
             from: "Parcel",
             localField: "parcelId",
             foreignField: "_id",
             as: "parcel"
         }
     },
     {
         $unwind: {
             path: "$parcel",
             preserveNullAndEmptyArrays: true
         }
     },
     {
         $lookup: {
             from: "ParcelStatus",
             localField: "parcel._id",
             foreignField: "parcelId",
             as: "parcel.parcelStatuses"
         }
     },
     {
         $lookup: {
             from: "Customer",
             localField: "parcel.customerData.customerId",
             foreignField: "_id",
             as: "parcel.customerData.customer"
         }
     },
     {
         $unwind: "$parcel.customerData.customer"
     }
 ])

现在在 PARCEL 对象中包含的 ParcelStatus 数组中,我需要检查

if(parcel.ParcelStatus.includes((x) => x.statusRepositoryId === 'ID's from frontend')
//then run $match on root against statusRepositoryId === 'SPECIFIC STATIC ID'

我不知道如何在聚合中做到这一点。您的帮助将不胜感激

标签: mongodbaggregation-framework

解决方案


只需添加此$match阶段:

{
    $match: {
        "parcel.parcelStatuses.statusRepositoryId": {$in: idArrayFromClient}
    }
}

推荐阅读