Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match with substring in mongodb aggregation

Tags:

regex

mongodb

In my mongodb collection, I have a time_stamp="2013-06-30 23:58:37 928". I need to use "$match" with only the date, like time_stamp="2013-06-30". So how can I get the substring like that ?

Previously I've tried with $substr, but it shows an error "errmsg" : "exception: invalid operator: $substr"

like image 351
Shashika Avatar asked Nov 19 '13 08:11

Shashika


People also ask

How do I match a string in MongoDB?

i: To match both lower case and upper case pattern in the string. m: To include ^ and $ in the pattern in the match i.e. to specifically search for ^ and $ inside the string. Without this option, these anchors match at the beginning or end of the string. x: To ignore all white space characters in the $regex pattern.

What does $match do in MongoDB?

The MongoDB $match operator filters the documents to pass only those documents that match the specified condition(s) to the next pipeline stage.

What is $Substr in MongoDB?

Definition. Deprecated since version 3.4: $substr is now an alias for $substrBytes . Returns a substring of a string, starting at a specified index position and including the specified number of characters. The index is zero-based.


1 Answers

I think you are trying to make query using aggregation framework since you tried $match & $substr operators. I have created a simple example to show how you can use $substr to achive result you wanted on aggregation framework.

I have inserted following data into the MongoDB.

{ "_id" : ObjectId("528b343881d4fe2cfe0b1b25"), "time_stamp" : "2013-06-30 23:58:37 928" }
{ "_id" : ObjectId("528b343b81d4fe2cfe0b1b26"), "time_stamp" : "2013-06-30 23:58:37 928" }
{ "_id" : ObjectId("528b344c81d4fe2cfe0b1b27"), "time_stamp" : "2013-06-30 12:58:37 928" }
{ "_id" : ObjectId("528b344f81d4fe2cfe0b1b28"), "time_stamp" : "2013-06-30 12:58:23 928" }
{ "_id" : ObjectId("528b345381d4fe2cfe0b1b29"), "time_stamp" : "2013-06-31 12:58:23 928" }
{ "_id" : ObjectId("528b345981d4fe2cfe0b1b2a"), "time_stamp" : "2013-07-31 12:58:23 933" }

I wrote following code to group by date by using $substr operator.

db.myObject.aggregate(
{$project : {new_time_stamp : {$substr : ["$time_stamp",0, 10]}}},
{$group:{_id:"$new_time_stamp", "count": {$sum:1}}}
);
like image 156
Parvin Gasimzade Avatar answered Nov 02 '22 16:11

Parvin Gasimzade