1

I'm trying write a script and get data from collections added in year and particular month.

And also get the records where 'Name' field matches my given regex.

Is it possible to use regex group in aggregate? Something like this :

collection1.aggregate([
     {"$match": {"$expr":{"$and":[{"$eq":[{"$year":"$updated_time"}, year]}, {"$eq":[{"$month":"$updated_time"}, month]}]}}},
{$group : {_id : {"Name": {"$regex": '^ABC', "$options": "i"} },count: { $sum: 1 }}
}]

Or which is the best way to get it? how do i modify this query to get count of regex match in that time frame

1 Answer 1

3

You can use $regex inside the $match itself and then use $count to get the number of matched document

collection1.aggregate([
  { "$match": {
    "$expr": {
      "$and": [
        { "$eq": [{ "$year": "$updated_time" }, year] },
        { "$eq": [{ "$month": "$updated_time" }, month] }
      ]
    },
    "Name": { "$regex": "^ABC", "$options": "i" }
  }},
  { "$count": "count" }
])

or either by $group as well

collection1.aggregate([
  { "$match": {
    "$expr": {
      "$and": [
        { "$eq": [{ "$year": "$updated_time" }, year] },
        { "$eq": [{ "$month": "$updated_time" }, month] }
      ]
    },
    "Name": { "$regex": "^ABC", "$options": "i" }
  }},
  { "$group": {
    "_id": null,
    "count": { "$sum": 1 }
  }}
])
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you that works !! Had another query im trying to output the data to another collection by grouping as below : { "$group": {"_id": null,"count": { "$sum": 1 }},"updated_time":{ "$push": "$updated_time" }}, { "$out" : "new_Coll" }.. But this is adding updates times as per count value. I want update_time only once in new collection
It will add count and the update_time array nothing else
Yeah update_time is added multiple times if the count is 5 updated_time is added 5 times. Is my push statement incorrect ?
Yes it will add 5 time as the number of documents are also 5.
is it possible to add only once ?
|

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.