skip to Main Content

I have object with column chars with such data:

{
  "chars": [
    {
      "count": 1,
      "color": "red"
    },
    {
      "count": 2,
      "color": "green"
    },
    {
      "count": 3,
      "color": "blue"
    }
  ]
}

I want to exclude records with chars like

{"count": 2, "color": "blue"}

I filter by (demo1)

{
    "$or": [
        {
            "chars.count": {
                "$ne": 2
            }
        },
        {
            "chars.color": {
                "$ne": "blue"
            }
        }
    ]
}

or (demo2)

{
    "chars.count": {
        "$ne": 2
    },
    "chars.color": {
        "$ne": "blue"
    }
}

I want to receive object, but receive empty set.

I use MongoDB 6.0.6

2

Answers


  1. Your query should be like this

    "$or": [
        { "chars.count": { "$ne": 2 } },
        { "chars.color": { "$ne": "blue" } }
      ]
    
    Login or Signup to reply.
  2. I think what you’re looking for is to use the $elemMatch query operator to match documents that have an array element containing { count: 2, color: "blue" } and just negate the results by using $not. This will return all documents that didn’t match, which I think is what you’re aiming for:

    db.collection.find({
      chars: {
        $not: {
          $elemMatch: {
            count: 2,
            color: "blue"
          }
        }
      }
    })
    

    See HERE for a working example.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search