Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

lookup with pipeline without specifying localfield and foreignfield

db.Products.aggregate([
  {
    $lookup: {
      from: "Products_History",
      localField: "_fid",
      foreignField: "_fid",
      as: "joins",
      pipeline: [
        {
          "$sort": {
            "date": -1
          }
        }
      ]
    }
  },
  {
    "$project": {
      "_fid": 1,
      "field1": 1,
      "field2": 1,
      "field3": 1,
      "last_version": {
        $first: "$joins.version"
      }
    }
  },
  {
    $match: {
      "last_version": {
        $exists: true
      }
    }
  }
])

This works well when MongoDB is version 5 or higher.

However, on my current version I am getting: "$lookup with ‘pipeline’ may not specify ‘localField’ or ‘foreignField’"

Is there a way to fix the query while still joining them. I don’t know of a different way to do this.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

https://mongoplayground.net/p/SYsmjYjOdNJ

>Solution :

You can use the old school "let and match" syntax.

db.Products.aggregate([
  {
    $lookup: {
      from: "Products_History",
      "let": {
        f: "$_fid"
      },
      as: "joins",
      pipeline: [
        {
          $match: {
            $expr: {
              $eq: [
                "$$f",
                "$_fid"
              ]
            }
          }
        },
        {
          "$sort": {
            "date": -1
          }
        }
      ]
    }
  },
  {
    "$project": {
      "_fid": 1,
      "field1": 1,
      "field2": 1,
      "field3": 1,
      "last_version": {
        $first: "$joins.version"
      }
    }
  },
  {
    $match: {
      "last_version": {
        $exists: true
      }
    }
  }
])

Mongo Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading