我正在使用聚合从子文档中分页数据.子文档没有严格的架构,因此每个文档的子文档可以有所不同,这使我难以构造输出,因为我不知道子文档的字段名称.
我在用什么
蒙戈3.0.0
节点0.10.33
猫鼬3.9.7
我的模特
var BodySchema = new Schema({random: String},{strict:false});
var FeedSchema = new Schema({
name: String,
body:[BodySchema]
});
我的数据看起来像这样
[{
_id:"...",
name:"Power Rangers feed",
body:[
{
"_id":"...",
"name" : "Jason",
"colour" : "Red",
"animal" : "T-rex"
},
{
"_id":"...",
"name" : "Billy",
"colour" : "Blue",
"animal" : "Triceratops"
},
{
"_id":"...",
"name" : "Zach",
"colour" : "Black",
"animal" : "Mastadon"
}
]
},
{
_id:"...",
name:"Transformers feed",
body:[
{
"_id":"...",
"name" : "Optimus Prime",
"team" : "Autobots",
"class" : "leader"
"alt-mode" : "truck"
},
{
"_id":"...",
"name" : "Bumblebee",
"team" : "Autobots",
"class" : "scout"
"alt-mode" : "VW Beetle"
},
{
"_id":"...",
"name" : "Blaster",
"team" : "Autobots",
"class" : "Commmunicator"
"alt-mode" : "Sterio"
},
{
"_id":"...",
"name" : "Hotrod",
"team" : "Autobots",
"class" : "Warrior"
"alt-mode" : "Car"
}
]
}]
我当前的汇总代码如下所示
feed.aggregate([
{'$match':{_id:id('550234d3d06039d507d238d8')}},
{'$unwind':'$body'},
{'$skip':2},
{'$limit':2},
{
'$project': {
'_id':"$body._id",
'body': "$body"
}
},
], function(err, result){
if(err){return(res.send(500, err))}
res.send(result);
});
我目前的结果看起来像这样
[{
_id:"...",
body:{
"_id":"...",
"name" : "Blaster",
"team" : "Autobots",
"class" : "Commmunicator"
"alt-mode" : "Sterio"
}
},
{
_id:"...",
body:{
"_id":"...",
"name" : "Hotrod",
"team" : "Autobots",
"class" : "Warrior"
"alt-mode" : "Car"
}
}]
我想要的结果看起来像这样
[
{
"_id":"...",
"name" : "Blaster",
"team" : "Autobots",
"class" : "Commmunicator"
"alt-mode" : "Sterio"
},
{
"_id":"...",
"name" : "Hotrod",
"team" : "Autobots",
"class" : "Warrior"
"alt-mode" : "Car"
}
]
我的问题
如何获得所需的结果结构.
解决方法:
因此,您将对此感到讨厌,但这就是聚合管道中的$project
和$group
阶段的工作方式.您需要“明确地”在输出中指定所需的所有字段.因此:
feed.aggregate([
{'$match':{_id:id('550234d3d06039d507d238d8')}},
{'$unwind':'$body'},
{'$skip':2},
{'$limit':2},
{
'$project': {
'_id':"$body._id",
'name': '$body.name',
'team': '$body.team',
'class': '$body.alt-mode'
}
},
], function(err, result){
那确实是唯一的方法.
但是,确实有很强的理由,并且大多数原理都在SQL SELECT中进行了备份,适用时*除外.
一般前提是,这类似于一般操作中的unix管道,因此,如果您认为:
grep | awk | sed
然后,这些操作在结构上似乎更加合乎逻辑.