feliixx / mongoplayground

a simple sandbox to test and share MongoDB queries
https://mongoplayground.net
GNU Affero General Public License v3.0
180 stars 11 forks source link

DB Randomly Does not Find Any Document #171

Open johachi opened 9 months ago

johachi commented 9 months ago

Description

The DB sometimes randomly returns "no documents" when using $elemMatch in the match.

Setup

Share link: https://mongoplayground.net/p/AylVo0AlDWF

Database type

bson

Database content

[
  {
    "_id": ObjectId("000000000000000000000111"),
    "triggers": [
      {
        "trigger": "sa",
        "method": "liveness_check",
        "source": {
          "service": "example",
          "type": "project",
          "identifier": "222222222222222222222222"
        }
      }
    ]
  },
  {
    "_id": ObjectId("000000000000000000000222"),
    "triggers": [
      {
        "trigger": "sa",
        "method": "liveness_check",
        "source": {
          "service": "example",
          "type": "project",
          "identifier": "111111111111111111111111"
        }
      }
    ]
  },
  {
    "_id": ObjectId("000000000000000000000333"),
    "triggers": []
  },
  {
    "_id": ObjectId("000000000000000000000444"),
    "triggers": [
      {
        "trigger": "sa",
        "method": "liveness_check",
        "source": {
          "service": "example",
          "type": "project",
          "identifier": "ff"
        }
      },
      {
        "trigger": "ff",
        "method": "liveness_check",
        "source": {
          "service": "example",
          "type": "project",
          "identifier": "222222222222222222222222"
        }
      }
    ]
  }
]

Query

db.collection.find({
  triggers: {
    $elemMatch: {
      "trigger": "sa",
      "method": "liveness_check",
      "source": {
        "service": "example",
        "type": "project",
        "identifier": "222222222222222222222222"
      }
    }
  }
})

Expected Result

[
  {
    "_id": ObjectId("000000000000000000000111"),
    "triggers": [
      {
        "method": "liveness_check",
        "source": {
          "identifier": "222222222222222222222222",
          "service": "example",
          "type": "project"
        },
        "trigger": "sa"
      }
    ]
  }
]

Actual Result

Sometimes same as the expected result, sometimes no document found

feliixx commented 7 months ago

Hi @johachi, sorry for the late answer.

It does look related to #153: here it looks like the query doesn't match anything when the source fields aren't correctly ordered. For example, this seems to always return correct results:

db.collection.find({
  triggers: {
    $elemMatch: {
      "trigger": "sa",
      "method": "liveness_check",
      "source.service": "example",
      "source.type": "project",
      "source.identifier": "222222222222222222222222"
    }
  }
})

playground link: https://mongoplayground.net/p/dumvPYTFSN7

I still need to figure a proper solution to this though