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)
                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: []}}
]
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: []}}
  ]
}
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)
                        Try this:
query = {
  $or: [
    {
      category: { $exists: false }
    },
    {
      category:[]
    }
  ]
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With