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.

1 Answer 1

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.

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

3 Comments

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.
If you are stuck with the old extensions I see no issue with using all of the functionality it provides including aggregations.
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.

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.