【发布时间】:2019-02-19 04:44:53
【问题描述】:
在开始使用聚合来创建文档的时间戳之前,我使用的是 findOne,所以我可以得到一个对象,但现在我得到一个包含单个对象的数组。是否可以使查询返回单个对象而不是数组?提前谢谢你。
我正在使用的查询:
News.aggregate()
.match({ '_id': n })
.project({ 'title': true, 'text': true, 'timestamp': { '$subtract': ['$date', new Date('1970-01-01')] } })
返回的是什么:
[
{
"_id": "5b9650beae847b1e5866cace",
"title": "Notícia 2",
"text": "Texto da Notícia 2",
"timestamp": 1543807353257
}
]
我想退货:
{
"_id": "5b9650beae847b1e5866cace",
"title": "Notícia 2",
"text": "Texto da Notícia 2",
"timestamp": 1543807353257
}
【问题讨论】:
-
聚合总是以数组的形式返回结果,你必须从中获取第 0 个索引。没有其他选择
-
感谢@AnthonyWinzlet
-
$unwind运营商将在这里提供帮助... -
$unwind 仅适用于文档中的数组字段,而不适用于整个结果数组。 @牧马人