PHP MongoDB. Check if embedded document contains integer

Viewed 27

I am new to MongoDB and trying to do an integer search in embeded documents. The collection I have is following

db.inventory.insertMany([{
    "store": "abc store",
    "games": [{
            "gameId": 12254,
            "score": 88
        },
        {
            "gameId": 12258,
            "score": 70
        },
        {
            "gameId": 12262,
            "score": 98
        }
    ]
}, {
    "store": "xyz store",
    "games": [{
            "gameId": 18244,
            "score": 88
        },
        {
            "gameId": 18248,
            "score": 25
        },
        {
            "gameId": 18252,
            "score": 66
        }
    ]
}]);

What I want to search in the collection is for example 122 in games.gameId and get the following result

[{
    "store": "abc store",
    "games": [{
            "gameId": 12254,
            "score": 88
        },
        {
            "gameId": 12258,
            "score": 70
        },
        {
            "gameId": 12262,
            "score": 98
        }
    ]
}]
1 Answers
  • $filter to iterate loo of games.gameId array of number
  • $toString to convert number to string
  • $regexMatch to match above converted string have any "122" string
  • $ne, the filtered result should not be empty []
  • $expr is expression condition to use aggregation operators
db.collection.find({
  $expr: {
    $ne: [
      {
        $filter: {
          input: "$games.gameId",
          cond: {
            $regexMatch: {
              input: { $toString: "$$this" },
              regex: "122"
            }
          }
        }
      },
      []
    ]
  }
})

Playground

  • php syntax if i am not wrong,
$query = [
  '$expr' => [
    '$ne' => [
      [
        '$filter' => [
          "input" => '$games.gameId',
          "cond" => [
            '$regexMatch' => [
              "input" => ['$toString' => '$$this'],
              "regex" => "122"
            ]
          ]
        ]
      ],
      []
    ]
  ]
];

$cursor = $collection->find($query);  
Related