Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible that mongodb's $project return an array?

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 would like to have:

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

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

like image 791
Varun Oberoi Avatar asked Oct 21 '13 18:10

Varun Oberoi


People also ask

What does $project do in MongoDB?

The $project takes a document that can specify the inclusion of fields, the suppression of the _id field, the addition of new fields, and the resetting of the values of existing fields. Alternatively, you may specify the exclusion of fields. Specifies the inclusion of a field.

How do I get an element from an array in MongoDB?

To search the array of object in MongoDB, you can use $elemMatch operator. This operator allows us to search for more than one component from an array object.


1 Answers

You could try with the $push operator.

For example, if you had documents like:

{ _id: <something>, y: 5 } 

In the mongo shell, if you type

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

You would get:

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

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

like image 191
Kay Avatar answered Sep 28 '22 04:09

Kay