Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
926 views
in Technique[技术] by (71.8m points)

regex - Match with substring in mongodb aggregation

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"

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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}}}
);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...