Valor_
Valor_

Reputation: 3601

Mongo db aggregate $elemMatch returns empty set

I'm trying to figure out what is the proper query for my current case. I have Mongo db documents, which looks like this

{ 
    "_id" : ObjectId("627e24df17446e1f646c945c"), 
    "phone_number" : "041041041", 
    "country" : "_si", 
    "blacklisted_service" : {
        "all" : false, 
        "place_order" : false, 
        "promo_code_sms" : true
    }, 
}

Now I'm trying to query documents, where "phone_number": 041041041 && "country" : "_si" AND ("blacklisted_service.all": true OR "blacklisted_service.promo_code_sms": true)...

Currently I'm trying to achieve my goal with aggregate & $elemMatch functions, but my results are always empty

db.getCollection("blacklisted_sms").aggregate([
    {
        $match: {
            phone_number: '041041041',
            country: '_si',
            blacklisted_service: {
                $elemMatch: {
                    'all': true,
                    $or: [
                        {
                            promo_code_sms: true,
                        }
                    ]
                },
            }
        }
    }
]);

Can you please help me define proper query, which will return a result if phone_number and country match in addition to check if one blacklisted_service key value is true. If you have any additional questions, please let me know and I will provide. I'm using mongo DB versions 4.x. Thank you in advance

Upvotes: 1

Views: 84

Answers (2)

Cere
Cere

Reputation: 93

db.collection.aggregate([
  {
    $match: {
      $and: [
        {
          "phone_number": "041041041"
        },
        {
          "country": "_si"
        },
        {
          $or: [
            {
              "blacklisted_service.all": true
            },
            {
              "blacklisted_service.promo_code_sms": true
            }
          ]
        }
      ]
    }
  }
])

Upvotes: 1

varman
varman

Reputation: 8894

You can try following,

db.collection.aggregate([
  {
    $match: {
      $expr: {
        $and: [
          { $eq: ["$phone_number", "041041041" ] },
          { $eq: [ "$country", "_si" ] },
          {
            $or: [
              { $eq: [ "$blacklisted_service.all", true ] },
              { $eq: [ "$blacklisted_service.promo_code_sms", true ] },
              
            ]
          }
        ]
      }
    }
  }
])

Working Mongo playground

Upvotes: 2

Related Questions