MongoDB聚合计数
我收集了用户和号码。每个数字都有AllocatedTouseId(ObjectId)字段,用户可以有多个数字。如何在单个查询中返回numberscont用户?这是我写的MongoDB聚合计数,mongodb,mongodb-query,aggregation-framework,Mongodb,Mongodb Query,Aggregation Framework,我收集了用户和号码。每个数字都有AllocatedTouseId(ObjectId)字段,用户可以有多个数字。如何在单个查询中返回numberscont用户?这是我写的 db.getCollection('Users').aggregate([ {'$lookup': {from: "Numbers", localField: "_id", foreignField: "AllocatedToUserId",
db.getCollection('Users').aggregate([
{'$lookup': {from: "Numbers",
localField: "_id",
foreignField: "AllocatedToUserId",
as: "Numbers"}
},{ '$project' : {_id:0,
document: '$$ROOT',
count: {$size:'$Numbers'}}}
])
但通过这个代码,我得到了如下响应结构:
[{document,count},{document,count},{document,count}…]
其中每个
文档
都有编号
集合,我希望计数
在文档内
和没有编号集合。可能吗?谢谢 您不必使用$$ROOT
系统变量投影另一个字段,只需从用户模式投影字段即可。下面的示例假定您有一个具有该架构的用户:
示例用户模式
{
"_id": ObjectId
"firstName": String,
"lastName": String,
"age": Integer,
"location": String
}
管道
db.getCollection('Users').aggregate([
{
"$lookup": {
"from": "Numbers",
"localField": "_id",
"foreignField": "AllocatedToUserId",
"as": "Numbers"
}
},
{
"$project": {
"firstName": 1,
"lastName": 1,
"age": 1,
"location": 1,
"Numbers": 0,
"count": { "$size": "$Numbers" }
}
}
])
谢谢是的,也许这是一个解决方案,但我的用户模式有25个字段。这就是为什么我使用了$$ROOT.With
$$ROOT
您仍然需要另一个$project
管道来展平文档
嵌入的文档所以。。这意味着这可能是最好的解决方案?除非严格要求有一个平坦的模式,否则我担心您可能必须$project
每个字段,否则$$ROOT
是一个更好的解决方案,因为您不必显式地投影字段。