Kon*_*kov 2 arrays mongodb mongodb-query aggregation-framework
我有诗集。集合中的文档具有以下结构:
{
"_id" : "Romeo and Juliet",
"acts" : [
{
"title" : "ACT I",
"scenes" : [
{
"title" : "SCENE I. Verona. A public place.",
"action" : [
{
"character" : "SAMPSON",
"says" : [
"Gregory, o' my word, we'll not carry coals."
]
},
{
"character" : "GREGORY",
"says" : [
"No, for then we should be colliers."
]
},
// ...
{
"character" : "GREGORY",
"says" : [
"To move is to stir; and to be valiant is to stand:",
"therefore, if thou art moved, thou runn'st away."
]
},
{
"character" : "SAMPSON",
"says" : [
"A dog of that house shall move me to stand: I will",
"take the wall of any man or maid of Montague's."
]
},
{
"character" : "GREGORY",
"says" : [
"That shows thee a weak slave; for the weakest goes",
"to the wall."
]
}
// ...
]
}
// ...
]
}
// ...
]}
Run Code Online (Sandbox Code Playgroud)
我想计算每首诗的行为和场景数量。我试图做这样的事情,但结果是不正确的。
db.poems.aggregate([{$unwind:"$acts"}, {$unwind:"$acts.scenes"}, {$group: {_id: "$_id", pa: {$push: {poemAct:"$acts"}}, ps: {$push: {poemScenes:"$acts.scenes"}}}}, {$project: {numberOfActs: {$size: "$pa"}, numberOfScenes: {$size: "$ps"}}}]).pretty()
Run Code Online (Sandbox Code Playgroud)
请帮助某人:D
您可以尝试以下聚合。没有$unwind需要在这里。
$map并$size输出具有场景大小$sum的数组并计算数组值。
db.poems.aggregate({
"$project":{
"numberOfActs":{"$size":"$acts"},
"numberOfScenes":{
"$sum":{
"$map":{
"input":"$acts",
"in":{"$size":"$$this.scenes"}
}
}
}
}
})
Run Code Online (Sandbox Code Playgroud)