假设我有这样的结构:
{
"_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}发布于 2020-06-12 18:36:41
您需要使用操作符将嵌套数组的扁平,并使用$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
}
}
])注意:如果嵌套数组为空,则跳过文档。
皮蒙戈
from bson.son import SON
pipeline = [
{"$unwind": "$acts" },
...
{"$sort": SON([("act", 1), ("speech", 1), ("line_count", 1)])}
]
result = list(db.collection.aggregate(pipeline))https://stackoverflow.com/questions/62343869
复制相似问题