D
D
Dmitry Prilepsky2021-01-25 23:43:11
MongoDB
Dmitry Prilepsky, 2021-01-25 23:43:11

How to query mongodb to filter by field type?

I have a field in my database. The general structure of this field is an Array with objects (a list of dictionaries). But there are also records where this field is just a dictionary. I need to fish out these records. I tried like this

{$and: [{'educations':{$type :'object'}}, {educations: {$ne: {$type: 'array'}}}]}

{educations:'object'}
But it didn't help me. How do I filter by field type?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir, 2021-01-26
@HartX

In this case, you need to use the $not operator to negate equality. Sample data:

db.test.insertMany([
  {
    "field1": "abc",
    "field2": [
      {"embeddedField": "a"},
      {"embeddedField": "b"},
      {"embeddedField": "c"}
    ]
  },
  {
    "field1": "xyz",
    "field2": {
      "embeddedField1": "x",
      "embeddedField2": "y",
      "embeddedField3": "z"
    }
  }
])

Request:
db.test.find({"field2": {$not: {$type: "array"}}})
Result:
{
  "_id": ObjectId("..."),
  "field1": "xyz",
  "field2": {
    "embeddedField1": "a",
    "embeddedField2": "b",
    "embeddedField3": "c"
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question