这是我的聚合管道:
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': {} } ])
返回:
/* 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
}
使用Robomongo 效果很好。我的nodejs代码:
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
id
就像这样(model.schema.paths._id.options.type)(query.article)
(因为我无法访问mongoose,只能访问模型。
发送的管道是这样的:
[ { '$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': {} } ]
如果我只是将id设置为字符串(没有ObjectId构造函数),它也不起作用。如果我删除了第一个管道($match
),它可以工作(但我希望它与此管道一起使用)。希望我很清楚。
答案 0 :(得分:1)
好问题来自我创建id的方式。这很有效:
id = model.base.Types.ObjectId(...);