mongodb的$ project是否可能返回数组? [英] Is it possible that mongodb's $project return an array?

查看:744
本文介绍了mongodb的$ project是否可能返回数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible for MongoDb's $project aggregation operator to restructure the document to an array ?

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

Here is what I did so far:

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

这给了我以下形式的输出:

This gives me output of form:

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

我想拥有:

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

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

I can easily restructure the output by iterating it, but really curious to know if aggregate itself could return array instead of object.

推荐答案

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

You could try with the $push operator.

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

For example, if you had documents like:

{ _id: <something>, y: 5 } 

在mongo shell中,如果您输入

In the mongo shell, if you type

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/

For more information on $push operator, see http://docs.mongodb.org/manual/reference/operator/aggregation/push/

这篇关于mongodb的$ project是否可能返回数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆