Mongo DB $$ROOT on 2.4

212 views
Skip to first unread message

gabrielstuff

unread,
Mar 12, 2015, 8:50:31 AM3/12/15
to mongod...@googlegroups.com
Hello,

I'm trying to implement a group by query using agregate.
Here is the query : 

db['cfs.medias.filerecord'].aggregate(
   
[
     
{
       $project
:
         
{
           year
: { $year: "$uploadedAt" },
           month
: { $month: "$uploadedAt" },
           day
: { $dayOfMonth: "$uploadedAt" },
           hour
: { $hour: "$uploadedAt" },
           minutes
: { $minute: "$uploadedAt" },
           seconds
: { $second: "$uploadedAt" },
           milliseconds
: { $millisecond: "$uploadedAt" },
           dayOfYear
: { $dayOfYear: "$uploadedAt" },
           dayOfWeek
: { $dayOfWeek: "$uploadedAt" },
           week
: { $week: "$uploadedAt" }
         
}
     
},
     
{ "$group" :
         
{ "_id" : {
               
"year" : "$year",
               
"month" : "$month",
               
"day" : "$day"
             
},
         
"medias": {
               
"$push":  {id:"$_id"}
               
}
         
}
     
}
   
]
);

I'd like to push the current document inside the medias Array instead of its id. How would one do that with mongo 2.4 ?

Thanks a lot !

Will Berkeley

unread,
Mar 12, 2015, 11:39:40 AM3/12/15
to mongod...@googlegroups.com
$$ROOT isn't available. As an approximation, you can use $addToSet or $push to add all the documents fields explicitly. For example,

> db.test.drop()
> db.test.insert({ "_id" : 0, "a" : 1, "b" : 2, "c" : 3 })
> db.test.insert({ "_id" : 1, "a" : 1, "b" : 4, "c" : 5 })
> db.test.aggregate([
   
{ "$group" : { "_id" : "$a", "bs" : { "$push" : "$b" }, "cs" : { "$push" : "$c" } } }
])
{ "_id" : 1, "bs" : [ 2, 4 ], "cs" : [ 3, 5 ] }


What are you trying to do with this pipeline, exactly? It's often a sort of anti-pattern to be trying to write a pipeline that wants to store all the documents of a group using $$ROOT, or, somewhat similarly, to want an output from a pipeline that looks like the documents from the original collection, though occasionally it's reasonable.

-Will

Reply all
Reply to author
Forward
0 new messages