2

I need to find all documents where an element of an array in that document matches a condition of it's fields:

{
  doc_id: 0,
  array_field: [
    { id: 0, min: 1, max: 2 },
    { id: 1, min: 1, max: 1 },
    ...
  ]
}
...

I need all documents where any object in array_field has a max != min.

I've been using $elemMatch to query the array elements (which works fine by itself), but I can't seem to make it work with an $expr:

{
  array_field: {
    $elemMatch: {
        $expr: { $ne: [ "$min", "$max" ]}
    }
  }
}

How do I correctly compare the fields within the array object?

2 Answers 2

3

You can't use aggregation operators with query operators. You can use $setDifference to compare min with max array and return if there are elements in the min array which are not in max array.

Use $expr with $setDifference. $expr allows use of aggregation expressions in the regular find query.

Something like

db.collection.find({
    "$expr":{
      "$ne":[
        {"$size":{"$setDifference":["$array_field.min","$$array_field.max"]}},
        0
      ]
    }
  }
)

You can also look at here to return when there is matching elements in arrays.

Comparing two object arrays and check if they have common elements

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

Comments

1
db.collection.aggregate([
{"$match":{
"$expr":{
  "$eq":[
    {"$size":{"$setIntersection":["$min","$max"]}},
    0
  ]
}
}},
    {"$project":{"_id":1}}
])

$setIntersection to compare the FirstArrays Names with SecondArrays Names and return array of common names documents followed by $size and $redact and compare result with 0 to keep and else remove the document.

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.