2

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

4
  • 1
    Like this demo? Commented Jul 29, 2024 at 12:05
  • Yes, but now not filters 3 and blue Commented Jul 29, 2024 at 12:23
  • Your question is unclear. You want the returned document with filtered chars in the projection? Should be filter 2 not 3 according to your question? Commented Jul 29, 2024 at 12:26
  • I want to receive whole object with array chars with all objects in it, because I haven't {"count": 2, "color": "blue"} Commented Jul 29, 2024 at 14:56

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

-2

Your query should be like this

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.