admin管理员组

文章数量:1391947

I am getting incorrect matched result in $lookup stage. Can you please explain what am I doing wrong?

Please see the following collections and code.

    "collection1": [
    {
      _id: ObjectId("67bf2c061d02c9e2f7978905"),
      "pos_v": 111,
      "ref_v": "a",
      "alt_v": "b",
      "gf": 0.2
    },
    {
      _id: ObjectId("67bf2c061d02c9e2f7978908"),
      "pos_v": 222,
      "ref_v": "a",
      "alt_v": "d",
      "gf_v": 0.145
    }
  ],

  "collection2": [
    {
      "pos": 111,
      "ref": "a",
      "alt": "b",
      "fieldx": "hdhdhfh"
    },
    {
      "pos": 324,
      "ref": "a",
      "alt": "s",
      "fieldx": "ssdf"
    }
  ]

The query I am running:

  db.collection1.aggregate([
  {
    $match: {
      _id: ObjectId("67bf2c061d02c9e2f7978905")
    }
  },
  {
    $lookup: {
      from: "collection2",
      let: {
        "pos_gv": "$pos",
        "ref_gv": "$ref",
        "alt_gv": "$alt"
      },
      pipeline: [
        {
          $match: {
            $expr: {
              $and: [
                {
                  $eq: [
                    "$$pos_gv",
                    "$pos_v"
                  ]
                },
                {
                  $eq: [
                    "$$ref_gv",
                    "$ref_v"
                  ]
                },
                {
                  $eq: [
                    "$$alt_gv",
                    "$alt_v"
                  ]
                }
              ]
            }
          }
        }
      ],
      as: "existingVariant"
    }
  },
  {
    "$unwind": "$existingVariant"
  }
])

See here:

Why is the result matching incorrectly? Result:

    [
  {
    "_id": ObjectId("67bf2c061d02c9e2f7978905"),
    "alt_v": "b",
    "existingVariant": {
      "_id": ObjectId("5a934e000102030405000002"),
      "alt": "b",
      "fieldx": "hdhdhfh",
      "pos": 111,
      "ref": "a"
    },
    "gf": 0.2,
    "pos_v": 111,
    "ref_v": "a"
  },
  {
    "_id": ObjectId("67bf2c061d02c9e2f7978905"),
    "alt_v": "b",
    "existingVariant": {
      "_id": ObjectId("5a934e000102030405000003"),
      "alt": "s",
      "fieldx": "ssdf",
      "pos": 324,
      "ref": "a"
    },
    "gf": 0.2,
    "pos_v": 111,
    "ref_v": "a"
  }
]

Expected Result:

[
  {
    "_id": ObjectId("67bf2c061d02c9e2f7978905"),
    "alt_v": "b",
    "existingVariant": {
      "_id": ObjectId("5a934e000102030405000002"),
      "alt": "b",
      "fieldx": "hdhdhfh",
      "pos": 111,
      "ref": "a"
    },
    "gf": 0.2,
    "pos_v": 111,
    "ref_v": "a"
  }
]

Did I misunderstand how match works?

本文标签: mongodb match in aggregation pipeline matching incorrect recordsStack Overflow