简体   繁体   中英

MongoDB - How to compare fields of different collections in $match of aggregate?

Let's suppose I have the collection A and the collection B . My query is like following:

db.A.aggregate([
    {
       $lookup: {
           from: "B",
           localField: "_id",
           foreignField: "custom_id",
           as: "B"
        }
    },
    {
     $match: {
           "B.anotherId": "A.anotherId" // not working, is it possible?
    }
])

I'm curious to know if it's possible to do what I tried to do in $match . The goal is to get only the documents that have the same "anotherId" value in A and B documents. Is it supported? And if yes, how do to it?

Not sure what you are trying to achieve here. $lookup provides an array of values. Are you trying to filter the array? Which would mean you have to use $filter. However, based on your question of how to compare two fields, you have to use $expr.

{
     $match: {
        $expr: {
            $eq: ["$firstField", "$secondField"]
       }
    }
}

If however you are trying to filter the collection B based on a value in A, you will have to use $filter

{
   $set: {
      B: {
         $filter: {
             input: "$B",
             as: "b",
             cond: {
                $eq: ["$A.anotherId", "$$b.anotherId"]
             }
         }
      }

   }
}

You can use $lookup with aggregation pipeline ,

  • let to define your both fields, and check expression condition in $match and $and
db.A.aggregate([
    {
        $lookup: {
            from: "B",
            let: {
                custom_id: "$_id",
                anotherId: "$anotherId
            },
            pipeline: [
                {
                    $match: {
                        $expr: {
                            $and: [
                                { $eq: ["$$custom_id", "$custom_id"] },
                                { $eq: ["$$anotherId", "$anotherId"] }
                            ]
                        }
                    }
                }
            ],
            as: "B"
        }
    }
])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM