在mongo聚合中匹配两个string对象字段

> 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即数组访问中的第一项 )并返回它的计数。 还想返回只有一个数组元素的访问数组数。

我怎样才能做到这一点?

当前arrays位置运算符不可用于聚合。 有一个未解决的未解决的问题: https : //jira.mongodb.org/browse/SERVER-4588和https://jira.mongodb.org/browse/SERVER-4589

您将不得不使用$first操作符来投影数组的第一个元素。 这下面的查询应该给你你想要的结果。 (我假设你想比较cur.hrefvisits[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 }