与mongodb聚合中的子字符串匹配 [英] Match with substring in mongodb aggregation

查看:256
本文介绍了与mongodb聚合中的子字符串匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的mongodb集合中,我有一个time_stamp = "2013-06-30 23:58:37 928" . 我只需要在日期上使用" $ match ",例如time_stamp =" 2013-06-30 ".那么如何获得这样的子字符串呢?

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 ?

以前我尝试过使用$ substr,但是它显示错误"errmsg":异常:无效的运算符:$ substr"

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

推荐答案

我认为您尝试使用聚合框架进行查询,因为您尝试了 $ substr 运算符.我创建了一个简单的示例,展示了如何使用 $ substr 来获得所需的结果在聚合框架上.

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.

我已将以下数据插入MongoDB.

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" }

我编写了以下代码,使用 $ substr 运算符按日期进行分组.

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

这篇关于与mongodb聚合中的子字符串匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆