Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using $$ROOT in aggregation order

I'm try get data from collection with some order:

db.data.aggregate([
    {$limit: 1000},
    {$group: {
        _id: "$service",
        count: {$sum: 1},
        data: {$push: '$$ROOT'}
    }}
]);

But get next error:

Error("Printing Stack Trace")@:0
()@src/mongo/shell/utils.js:37
([object Array])@src/mongo/shell/collection.js:866
@(shell):6

uncaught exception: aggregate failed: {
    "errmsg" : "exception: FieldPath field names may not start with '$'.",
    "code" : 16410,
    "ok" : 0
}

Where did I go wrong?

like image 542
vporoshok Avatar asked Apr 11 '14 11:04

vporoshok


People also ask

What is $$ root MongoDB?

$replaceRoot. Replaces the input document with the specified document. The operation replaces all existing fields in the input document, including the _id field. You can promote an existing embedded document to the top level, or create a new document for promotion (see example).

How do I sort aggregation in MongoDB?

In MongoDb, the aggregation is assisted by several methods and operators that can perform different tasks. Among those operators, the $sort operator helps to sort the documents and return the documents in an organized order. And for group sorting in MongoDB, the $group operator is used with the $sort operator.

What is $Not in aggregation?

Definition. Evaluates a boolean and returns the opposite boolean value; i.e. when passed an expression that evaluates to true , $not returns false ; when passed an expression that evaluates to false , $not returns true . For more information on expressions, see Expressions.


1 Answers

So per the comment you need a MongoDB version 2.6 do do this. But of course using 2.6 this works for me:

db.collection.aggregate([
    { "$limit": 1000 }, 
    { "$group": { 
        "_id": null, 
        "count": { "$sum": 1}, 
        "data": { "$push": "$$ROOT"  }
    }}
])
like image 93
Neil Lunn Avatar answered Oct 11 '22 13:10

Neil Lunn