This is my aggregation pipelines:
db.articles.aggregate([ { '$match': { _id: ObjectId('5422d579466673f01a84c82f') } },
{ '$unwind': '$comments' },
{ '$project':
{ content: '$comments.content',
author: '$comments.author',
created_at: '$comments.created_at',
_id: '$comments._id',
article: '$_id' } },
{ '$skip': 0 },
{ '$limit': 15 },
{ '$match': {} } ])
This returns:
/* 0 */
{
"result" : [
{
"_id" : ObjectId("5422d5a9466673f01a84c830"),
"created_at" : ISODate("2014-09-24T14:31:05.644Z"),
"article" : ObjectId("5422d579466673f01a84c82f")
},
{
"_id" : ObjectId("5422d5b4466673f01a84c831"),
"content" : "foo",
"created_at" : ISODate("2014-09-24T14:31:16.606Z"),
"article" : ObjectId("5422d579466673f01a84c82f")
}
],
"ok" : 1
}
This works well using Robomongo. My nodejs code:
pipelines = [
{
$match: {_id: id}
},
{
$unwind: "$#{@location}"
},
{
$project: project
},
{
$skip: query.skip or query.offset or 0
},
{
$limit: query.limit or 15
},
if query.sort then {
$sort: if query.sort and query.sort[0] is '-'
obj = {}
obj[query.sort.substring(1)] = -1
obj
else if query.sort
obj = {}
obj[query.sort] = 1
obj
},
{
$match: match
}
]
@model.aggregate _.compact(pipelines), (err, result) ->
if err then return deferred.reject err
deferred.resolve result
The id is like this (model.schema.paths._id.options.type)(query.article) (because I don't have access to mongoose, only the model.
The pipelines sent are like this:
[ { '$match':
{ _id:
{ path: '5422d579466673f01a84c82f',
instance: 'ObjectID',
validators: [],
setters: [],
getters: [],
options: undefined,
_index: null } } },
{ '$unwind': '$comments' },
{ '$project':
{ content: '$comments.content',
author: '$comments.author',
created_at: '$comments.created_at',
_id: '$comments._id',
article: '$_id' } },
{ '$skip': 0 },
{ '$limit': 15 },
{ '$match': {} } ]
And if I just set the id as a string (without ObjectId constructor), it doesn't works either. If I remove the first pipeline ($match) it works (but I want it with this pipeline). Hope I'm clear.
OK The problem came from the way I created the id. This worked:
id = model.base.Types.ObjectId(...);