У меня ниже структура 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 и pu sh в один новый массив.
Мой ожидаемый ответ.
{
_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