【发布时间】:2020-07-14 23:24:19
【问题描述】:
我有以下 mongodb 结构
{
"userId" : "5d3014fe56db690a5959a870",
"contentId" : "1",
"userAnswer" : {
"uploads" : [
"123",
"456"
]
}
},
{
"userId" : "5d3014fe56db690a5959a8700",
"contentId" : "1",
"userAnswer" : {
"uploads" : [
"789"
]
},
},
{
"userId" : "5d3014fe56db690a5959a874",
"contentId" : "2",
"userAnswer" : {
"uploads" : [
null
]
}
}
contentId 有 (userAnswer.uploads) 123 & 456 & 789。我想根据 contentId 进行计数并推入一个新数组。
我的预期答案。
{
_id: 1,
totalCount : 3
},
{
_id: 2,
totalCount : 0
}
我的代码
db.test.aggregate([
{ $project : { "contentID":"$contentId", "regularStudent" : "$userAnswer.uploads"} },
{ $group : { _id : "$contentID", regularStudent: { $push: "$regularStudent" } } },
{ $project: { "regularStudent": { "$reduce": { "input": "$regularStudent", initialValue: [], "in": { $concatArrays: [ "$$this", "$$value" ] } } } } },
{ $project: { totalStudent: { $cond: { if: { $isArray: "$regularStudent" }, then: { $size: "$regularStudent" }, else: "NA"} } } }
])
我的输出
/* 1 */`enter code here`
{
"_id" : "2",
"totalStudent" : 1
},
/* 2 */
{
"_id" : "1",
"totalStudent" : 3
}
MongoDb 3.4 版
我是新的mongodb
【问题讨论】:
标签: mongodb mongodb-query