Search code examples
pythonmongodbtypesmongodb-compass

type in mongodb not filtering record properly


Applying Filter

{'info.version': { $type: "string" }}

Output of above filter

c
python
java
ubuntu

MongoDB Version: 3.6.3

Data in MongoDB(Consider every list element as single document)

[
  {
    "name": "c",
    "info": {
      "version": "2.0"
    }
  },
  {
    "name": "python",
    "info": {
      "version": [
        "2.0",
        "3.0"
      ]
    }
  },
  {
    "name": "java",
    "info": {
      "version": [
        "11.0"
      ]
    }
  },
  {
    "name": "ubuntu",
    "info": {
      "version":"20"
    }
  }
]

Expected Result

c(Record)
ubuntu(record)

Is I am missing something while applying filter?


Solution

  • You have to use this

    await db.aggregate([
            {
                $match: {
                    "info.version": { $type: "string",$not: {$type: "array" } }
                },
            }
    
        ]).toArray()