【发布时间】:2018-03-05 14:25:20
【问题描述】:
我有一个 Mongo 集合,其中包含这样的文档:
{
"_id" : ObjectId("5a9d0d44c3a1ce5f14c6940a"),
"topic_id" : "5a7af30613b79405643e7da1",
"value" : "VMware Virtual Platform",
"timestamp" : "2018-03-05 09:26:25.136546",
"insert_ts" : "2018-03-05 09:26:25.136682",
"inserted_by" : 1
},
{
"_id" : ObjectId("5a9d0d44c3a1ce5f14c69409"),
"topic_id" : "5a7af30713b79479f82b4b84",
"value" : "VMware, Inc.",
"timestamp" : "2018-03-05 09:26:25.118931",
"insert_ts" : "2018-03-05 09:26:25.119081",
"inserted_by" : 1
},
{
"_id" : ObjectId("5a9d0d44c3a1ce5f14c69408"),
"topic_id" : "5a7af30713b7946d6d0a8772",
"value" : "Phoenix Technologies LTD 6.00 09/21/2015",
"timestamp" : "2018-03-05 09:26:25.101624",
"insert_ts" : "2018-03-05 09:26:25.101972",
"inserted_by" : 1
}
我想从这个集合中获取一些聚合数据。我想知道最早的时间戳、文档数和所有值的总strlen,但按topic_id分组,其中document-id大于x。
在 mysql 中,我会像这样构建一个 sql:
SELECT
MAX(_id) as max_id,
COUNT(*) as message_count,
MIN(timestamp) as min_timestamp,
LENGTH(GROUP_CONCAT(value)) as size
FROM `dev_topic_data_numeric`
WHERE _id > 22000
GROUP BY topic_id
我如何在 MongoDB 中实现这一点?我已经尝试过构建它,如下所示:
db.getCollection('topic_data_text').aggregate(
[
{
"$match":
{
"_id": {"$gte": ObjectId("5a9d0aefc3a1ce5f14c68c81") }
}
},
{
"$group":
{
"_id": "$topic_id",
"max_id": {"$max":"$_id"},
"min_timestamp": {"$min": "$timestamp"},
"message_count": {"$sum": 1},
/*"size": {"$strLenBytes": "$value" }*/
}
}
]
);
然后我取消注释 $strLenBytes 它崩溃说 strLenBytes 不是组运算符。 API of MongoDB 在这里对我没有帮助。怎么写才能得到strlen?
我的预期结果应该是这样的:
{
"_id" : "5a7af30613b79405643e7da1",
"max_id" : ObjectId("5a9d0d44c3a1ce5f14c6940a"),
"min_timestamp" : "2018-03-05 09:26:25.136546",
"message_count" : 1,
"size" : 23,
}
我的 MongoDB 版本是 3.4.4。
【问题讨论】:
-
你能添加预期的输出吗?
-
你试过
"size": { "$sum": {"$strLenBytes": "$value" } }吗? -
@RahulSharma 完成。
-
@chridam 我检查了你的建议。结果错误显示“无效的运算符 $strLenBytes”
-
我得到的最接近的结果是使用 {"$push":"$value"} ...但这并不是我想要得到的结果。
标签: mongodb aggregation-framework aggregate