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
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.