> db.doc.find().pretty();
{
"_id" : ObjectId("55669401a5f628a23fed5adc"),
"cur" : {
"pathname" : "/blog",
"href" : "http://www.example.com/blog/"
},
"visits" : [
{
"url" : "http://www.example.com/blog/",
"gt_ms" : "1110"
}
]
}
{
"_id" : ObjectId("556697eba5f628a23fed5add"),
"cur" : {
"pathname" : "/twcontroller/insights/login.php",
"href" : "http://www.example.com/twcontroller/insights/login.php"
},
"visits" : [
{
"url" : "http://www.example.com/twcontroller/insights/login.php",
"gt_ms" : "990"
}
]
}
{
"_id" : ObjectId("556697eba5f628a23fed5ade"),
"cur" : {
"pathname" : "/",
"href" : "http://www.example.com/"
},
"visits" : [
{
"url" : "http://www.example.com/",
"gt_ms" : "719"
},
{
"url" : "http://www.example.com/",
"gt_ms" : "719"
}
]
}
{
"_id" : ObjectId("556697eba5f628a23fed5adf"),
"cur" : {
"pathname" : "/",
"href" : "http://www.example.com/"
},
"visits" : [
{
"url" : "http://www.example.com/",
"gt_ms" : "62"
},
{
"url" : "http://www.example.com/",
"gt_ms" : "62"
},
{
"url" : "http://www.example.com/",
"gt_ms" : "62"
},
{
"url" : "http://www.example.com/",
"gt_ms" : "62"
},
{
"url" : "http://www.example.com/",
"gt_ms" : "62"
},
{
"url" : "http://www.example.com/",
"gt_ms" : "62"
},
{
"url" : "http://www.example.com/",
"gt_ms" : "62"
}
]
}
我想将cur.pathname
的值与visits[0].url
(,即数组访问中的第一项)匹配并返回其计数。还想返回只有一个数组元素的visit数组。
我该怎么做?
答案 0 :(得分:4)
目前阵列位置运算符不可用于聚合。有一个未解决的未解决的问题与其相关联:https://jira.mongodb.org/browse/SERVER-4588和https://jira.mongodb.org/browse/SERVER-4589。
您必须使用$first
运算符来投影数组的第一个元素。
以下查询应该为您提供所需的结果。 (我假设您要比较cur.href
和visits[0].url
。)
db.Testing.aggregate([
{
"$project": {
"hasOneElement": {
"$cond": [
{ "$eq": [{"$size": "$visits"}, 1] },
1,
0
]
},
"href": "$cur.href",
"visits.url" : 1
}
},
{'$unwind': '$visits'},
{'$group': {
'_id': "$_id",
'href': {'$first': '$href'},
'visits': {'$first': '$visits'},
'hasOneElement': {'$first': '$hasOneElement'}
}
},
{
'$project': {
'hasOneElement': 1,
"isMatch": {
"$cond": [
{ "$eq": ["$href", "$visits.url"] },
1,
0
]
}
}
},
{
'$group': {
'_id' : 'test',
'visit_count' : {'$sum' : '$isMatch' },
'oneelement_count' : {'$sum' : "$hasOneElement" }
}
}
])
提供样本文件的结果。
{
"result" : [
{
"_id" : "test",
"visit_count" : 4,
"oneelement_count" : 2
}
],
"ok" : 1
}