Home > OS >  MongoDB Match Negative All
MongoDB Match Negative All

Time:09-30

Mongo Playground

Lets say I have docs with 3 props, FieldA, B, C.

I would like to do a match of all docs that don´t have the 3 props null.

I am trying $all, $nor, $not, $ne, etc... but none are working.

Ex.

[
  { "FieldA": 1, "FieldB": 1, "FieldC": 1,},              //1
  { "FieldA": 1, "FieldB": null, "FieldC": null,},        //2
  { "FieldA": null, "FieldB": 1, "FieldC": null,},        //3
  { "FieldA": null, "FieldB": null, "FieldC": 1,},        //4
  { "FieldA": null, "FieldB": null, "FieldC": null,},     //5
]

In my aggregation, I need to match all from 1st to 4th, but not 5th.

Get only the 5th is easy, but I need the negative of that.

cheers

CodePudding user response:

You can do it like this:

db.collection.aggregate([
  {
    "$match": {
      "$expr": {
        "$or": [
          {
            "$ne": [
              "$FieldA",
              null
            ]
          },
          {
            "$ne": [
              "$FieldB",
              null
            ]
          },
          {
            "$ne": [
              "$FieldC",
              null
            ]
          }
        ]
      }
    }
  }
])

Working example

CodePudding user response:

The not operator takes only one argument expression. Link

You can try instead using an and/or operator

db.collection.aggregate([
  {
    $match: {
      $or: [
        {
          "FieldA": {
            "$ne": null
          }
        },
        {
          "FieldB": {
            "$ne": null
          }
        },
        {
          "FieldC": {
            "$ne": null
          }
        }
      ]
    }
  }
])
  • Related