Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: Unknown operator: $or

I'm trying to do a simple or query for mongoDB, but I do get the error MongoError: unknown operator: $or

Could someone explain what I am doing wrong?

const query = {
  title: { $exists: true },
  category: { $exists: true, $ne: [] }
}

// ...do some stuff
// now need to change category query...

query.category = {
  $or: [
    { $exists: false },
    { $eq: [] }
  ]
}

// should return documents with missing category field or empty array value
Content.find(query)
like image 321
user3142695 Avatar asked Jan 30 '18 20:01

user3142695


2 Answers

The short answer is that the $or statement doesn't apply to a single field, but rather must have the field specified for each item:

$or: [
  {category: {$exists: false}},
  {category: {$eq: []}}
]

Explanation

Per the manual, the $or syntax is as follows:

{ $or: [ { <expression1> }, { <expression2> }, ... , { <expressionN> } ] }

Note that unlike a lot of operators, it does not include a field name. For instance, contrast $exists, which does include the field name:

{ field: { $exists: <boolean> } }

In other words, rather than:

{
  title: { $exists: true },
  category: {
    $or: [
      {$exists: false},
      {$eq: []}
    ]
  }
}

you need:

{
  title: { $exists: true },
  $or: [
    {category: {$exists: false}},
    {category: {$eq: []}}
  ]
}

Question's example

Putting it all together with your exact example, you end up with:

const query = {
  title: { $exists: true },
  category: { $exists: true, $ne: [] }
}

// ...do some stuff
// now need to change category query...

delete query.category
query.$or = [
  {category: {$exists: false}},
  {category: {$eq: []}}
]

// should return documents with missing category field or empty array value
Content.find(query)
like image 147
M. Justin Avatar answered Oct 10 '22 14:10

M. Justin


Try this:

query = {
  $or: [
    {
      category: { $exists: false }
    },
    {
      category:[]
    }
  ]
}
like image 44
Jithin Joy Avatar answered Oct 10 '22 13:10

Jithin Joy