skip to Main Content

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

2

Answers


  1. You can do it like this:

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

    Working example

    Login or Signup to reply.
  2. 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
              }
            }
          ]
        }
      }
    ])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search