11

MongoDb 的 $project 聚合运算符是否可以将文档重组为数组?

这是我到目前为止所做的:

var pipeline = [];
var project = {
    $project : {
        x: "$_id", 
        y: "$y" ,
        _id : 0
    }
};
pipeline.push(project);
model.aggregate( pipeline, callback);

这给了我形式的输出:

[
  { 
   x: '...',
   y: '...'
  }
 ....
]

我想拥有:

[
   ['..','..']
   ....
]

我可以通过迭代轻松地重构输出,但真的很想知道聚合本身是否可以返回数组而不是对象。

4

2 回答 2

4

您可以尝试使用 $push 运算符。

例如,如果您有以下文件:

{ _id: <something>, y: 5 } 

在 mongo shell 中,如果你输入

db.model.aggregate( [ { $group: { _id: null, newArrayField: { $push: {  x: "$_id", y: "$y"  } } } } ] )

你会得到:

{
    "result" : [
        {
            "_id" : null,
            "newArrayField" : [
                {
                    "x" : ObjectId("5265dd479eb4b1d4289cf222"),
                    "y" : 5
                }
            ]
        }
    ],
    "ok" : 1
}

有关 $push 运算符的更多信息,请参阅http://docs.mongodb.org/manual/reference/operator/aggregation/push/

于 2013-10-22T02:10:00.957 回答
1

使用 MongoDB 3.2,您可以投影数组值

db.model.aggregate({
  $project: {arrayField: ['$_id', '$y']}
})
于 2017-03-01T05:20:30.147 回答