0

I need to perform a MongoDB aggregation in PHP.

I read about the MongoCollection::aggregate method but to use the MongoCollection class I need to go through the MongoClient class, which is deprecated.

In the docs it is said to use the MongoDB driver instead and the MongoDB\Driver\Manager class. I already use this class for all my queries, updates and inserts, but I can't find a way to execute aggregations.

This topic does not help me because it uses regular queries.

I am quite surprised I can't find any answers out there.

Maybe I am focusing on aggregations while I don't need them so here is what I am trying to do:
I have a users collection that contains a peels field which is an array of string.
I would like to count for a given user the number of elements of its peels field matching a specific regex.

For instance, if I have this user:

{
  "_id": ObjectId("5ff337f8415b0000f9003b78"),
  "name": "Foo",
  "peels": [
    "2021-03-08",
    "2021-04-19",
    "2020-07-20",
    "2020-08-10"
  ]
}

I want to get the number of dates of the user for the year 2021, so matching the regex 2021-*. This should give me 2.

If this can indeed be solved without aggregations it would still be interesting to know how to use aggregation with the MongoDB/Driver/Manager or any other solution that is not deprecated.

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
MuZak
  • 181
  • 5
  • 14

1 Answers1

1

https://www.php.net/manual/en/mongocollection.aggregate.php is part of deprecated extension. It's not the client that is deprecated as per https://www.php.net/manual/en/class.mongoclient.php, the entire extension is.

The replacement is an extension and a higher-level library. https://www.php.net/manual/en/set.mongodb.php is the extension. https://docs.mongodb.com/php-library/master/tutorial/ is the library. You should use the library unless you have a specific reason to use the extension.

https://docs.mongodb.com/php-library/master/tutorial/crud/#complex-queries-with-aggregation shows an aggregation example with the library.

D. SM
  • 13,584
  • 3
  • 12
  • 21
  • Thank you for your answer. Unfortunatly I don't have the `MongoDB\Client` class or the `MongoDB\Collection` class availables on my server and I can't change the configuration. I will use queries and PHP to do the math, but your answer seems to be what I was looking for. – MuZak Jan 11 '21 at 08:38
  • If you are stuck with the old extensions I see no issue with using all of the functionality it provides including aggregations. – D. SM Jan 13 '21 at 07:39
  • You're right but I don't have the MongoClient class available either. I don't know what exactly was installed on the server but that is definitely not enough. – MuZak Jan 13 '21 at 12:09