首页 > 解决方案 > Not getting correct result with aggregate and pipeline

问题描述

Having issues with using the pipeline and getting the correct data back in my aggregate query. I have two collections where they both share a common id (eventId) that I want to use to "join" these collections.

Document from collection Pool

{
  "_id": ObjectId("5e1ebbc6cffd4b042fc081ab"),
  "eventId": "ABC_2020-01-15_40_1",
  "trackName": "Foo",
  "type": "bar"
}

Document from collection Races (multiple ones with same eventID

{
  "_id": ObjectId("5e1ebbc6cffd4b042fc081a1"),
  "eventId": "ABC_2020-01-15_40_1",
  "Data": {foo:"bar"}
}

The data I get back includes all the documents from the races collection, it seems that the pipeline is not running as I get the same result as if pass in an [] in the pipeline. I would like to getting some help figuring this out as I only want the ones with the same eventId in both collections in the result.

const result = await PoolModel.aggregate([

        {
          $match: {
            eventId,
          },
        },
        {
          $lookup: // join two collections
          {
            from: 'races', // races collection
            let: { eventId: '$event.eventId' }, // define vars to use in pipeline
            pipeline: [
                { $match: { $expr: ['$eventId', '$$eventId']  } },

                { $project: projection },
            ],
            as: 'races', // Display in new result as as

          },
        },

      ]);

This is my result:

 result: [ { _id: 5e1ebbc6cffd4b042fc081ab,
        eventId: 'ABC_2020-01-15_40_1',
        trackName: 'Foo',
        type: 'bar',
        races:
         [ [Object], // Wrong id 
           [Object], // Wrong id 
           [Object], // Wrong id 
           [Object], // Wrong id 
           [Object], // Wrong id 
           [Object], // Wrong id 
           [Object], // Wrong id 
           [Object], // Correct id
           [Object], // Correct id
           [Object], // Correct id
           [Object], // Correct id
           [Object], // Correct id
           [Object], // Correct id
           [Object], // Correct id
           [Object] ] } ]

标签: mongodbmongoose

解决方案


In the pipeline on the joined collection, $expr is expecting a conditional comparison operator (with an example to use it in a $lookup pipeline here) and you have given it none so in essence there is no filtering going on.

You would rather use the $eq operator as

{ '$match': { '$expr': { '$eq': ['$eventId', '$$eventId'] } } },

推荐阅读