MongoDb 试图对嵌入文档进行计数
MongoDb trying to count inside embedded documents
I have a document which looks like this
{'name':'abc',
'location': 'xyz',
'social_links' : { 'facebook' : 'links',
'Whosebug': 'links',
'quora' : 'links' ... }
}
I want to count the total number of links for each social_links in my collection
Currently my code looks like this
db.main_candidate.aggregate( [ { '$match': {'social_links.quora': {'$exists': true}}}, {'$group': { '_id' :'quora', 'count': {'$sum':1 }}}])
While this is correctly returning the counts for the specific social_link, I want to write a query which will be able to count for all the social_links in a single query instead of having to write for each specific name.
我认为如果不对特定名称进行硬编码,就无法通过查询对您想要的内容进行分组。也许您应该尝试使用 MapReduce。
您应该将 social_links 存储为数组而不是文档,这对我来说更有意义。类似于:
{'name':'abc',
'location': 'xyz',
'social_links' : [ { 'name':'facebook', 'link' : 'links'},
{ 'name':'quora', 'link' : 'links'},
{ 'name':'Whosebug', 'link' : 'links'}]
}
那么你可以进行如下查询:
db.col.aggregate(
{
$unwind: "$social_links"
},
{
$group:
{
_id: "$social_links.name",
count: $sum: 1
}
})
I have a document which looks like this
{'name':'abc',
'location': 'xyz',
'social_links' : { 'facebook' : 'links',
'Whosebug': 'links',
'quora' : 'links' ... }
}
I want to count the total number of links for each social_links in my collection Currently my code looks like this
db.main_candidate.aggregate( [ { '$match': {'social_links.quora': {'$exists': true}}}, {'$group': { '_id' :'quora', 'count': {'$sum':1 }}}])
While this is correctly returning the counts for the specific social_link, I want to write a query which will be able to count for all the social_links in a single query instead of having to write for each specific name.
我认为如果不对特定名称进行硬编码,就无法通过查询对您想要的内容进行分组。也许您应该尝试使用 MapReduce。
您应该将 social_links 存储为数组而不是文档,这对我来说更有意义。类似于:
{'name':'abc',
'location': 'xyz',
'social_links' : [ { 'name':'facebook', 'link' : 'links'},
{ 'name':'quora', 'link' : 'links'},
{ 'name':'Whosebug', 'link' : 'links'}]
}
那么你可以进行如下查询:
db.col.aggregate(
{
$unwind: "$social_links"
},
{
$group:
{
_id: "$social_links.name",
count: $sum: 1
}
})