skip to Main Content

I have these documents:

[
    {
        "id": 1,
        "condition": true
    },
    {
        "id": 1,
        "condition": false
    },
    {
        "id": 2,
        "condition": true
    },
]

In this case I want the output to be "id": 1, since it has condition as both true and false ("id": 2 only has condition as true, so it does not qualify)

Thank you

2

Answers


  1. you could create an aggregation pipeline in a way first group by id and get an array of conditions. then check if the condition array has true and false and create condition existing fields cond_true,cond_false.
    If both the cond_true and cond_false are true it is a match.

    db.collection.aggregate([
      {
        $group: {
          _id: "$id",
          conditions: { $push: "$condition" }
        }
      },
      {
        $project: {
          _id: 0,
          id: "$_id",
          cond_true: { $in: [ true, "$conditions" ] },
          cond_false: { $in: [ false, "$conditions" ] }
        }
      },
      {
        $match: { cond_true: true, cond_false: true }
      },
      {
        $project: { id: 1 }
      }
    ])
    

    playground

    Login or Signup to reply.
  2. One option is to use $setIsSubset for the generic case of n out of m wanted conditions:

    db.collection.aggregate([
      {$group: {
          _id: "$id",
          conditions: {$addToSet: "$condition"}
      }},
      {$match: {$expr: {
            $setIsSubset: [
              [true, false],
              "$conditions"
            ]
          }
      }},
      {$project: {id: 1}}
    ])
    

    See how it works on the playground example

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