假设我具有此结构:
{
"_id": "Henry IV",
"acts": [
{
"_id": "ACT I",
"scenes": [
{
"_id": "SCENE I. London. The palace.",
"speeches": [
{
"_id": 1,
"speaker": "KING HENRY IV",
"lines": [
{
"_id": "1.1.1",
"text": "So shaken as we are, so wan with care,"
},
{
"_id": "1.1.2",
"text": "Find we a time for frighted peace to pant,"
},
{
"_id": "1.1.3",
"text": "And breathe short-winded accents of new broils"
}]
},
{
"_id": 2,
"speaker": "WESTMORELAND",
"lines": [
{
"_id": "1.1.34",
"text": "My liege, this haste was hot in question,"
},
{
"_id": "1.1.35",
"text": "And many limits of the charge set down"
}]
}]
}]
}]
}
¿如何获得按“行”数排序的结果,并同时具有父节点属性?理想的结果如下所示:
{'play': 'Henry IV', 'act': 'ACT I', 'scene': 'SCENE I. London. The palace.', 'speech', '1', 'speaker': 'KING HENRY IV', 'line_count': 3}
{'play': 'Henry IV', 'act': 'ACT I', 'scene': 'SCENE I. London. The palace.', 'speech', '2', 'speaker': 'WESTMORELAND', 'line_count': 2}
您需要使用$unwind
运算符flatten嵌套数组,并使用$project
运算符将其转换为所需的输出,如下所示:
db.collection.aggregate([
{
$unwind: "$acts"
},
{
$unwind: "$acts.scenes"
},
{
$unwind: "$acts.scenes.speeches"
},
{
$project: {
_id: 0,
play: "$_id",
act: "$acts._id",
scene: "$acts.scenes._id",
speech: "$acts.scenes.speeches._id",
speaker: "$acts.scenes.speeches.speaker",
line_count: {
$size: "$acts.scenes.speeches.lines"
}
}
},
//Add here your sorting condition
{
$sort: {
act: 1,
speech: 1,
line_count: 1
}
}
])
注意:如果任何嵌套数组为空,则将跳过文档